Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Programação Funcional com Acarajé e Dendê

Programação Funcional com Acarajé e Dendê

Escreva códigos JavaScript mais elegantes e reutilizáveis utilizando conceitos de programação funcional. Vou mostrar tudo o que precisa saber para tirar o máximo proveito desse paradigma que vem se tornando cada vez mais importante para os problemas atuais.

Jonata Weber

November 26, 2016
Tweet

More Decks by Jonata Weber

Other Decks in Technology

Transcript

  1. f( )
    PROGRAMAÇÃO
    let author = {name: "Jonata Weber"}

    View Slide

  2. HELLO
    Jonata Weber

    View Slide

  3. facebook.com/devfsa

    View Slide

  4. www.app2sales.com

    View Slide

  5. View Slide

  6. Feijão Fradinho

    View Slide

  7. Aprendendo a dirigir

    View Slide

  8. Segundo carro

    View Slide

  9. Spaceship

    View Slide

  10. Functional
    Programming

    View Slide

  11. View Slide

  12. Quem está usando

    View Slide

  13. O que é uma função?
    É uma relação* entre um input e um output.
    -- mathsisfun.com

    View Slide

  14. View Slide

  15. Exemplo: uma relação x => x ^ 2

    View Slide

  16. (One-to-many) (Many-to-one)
    Relacionamento: input vs output

    View Slide

  17. Pure
    Functions

    View Slide

  18. Slice vs Splice
    var xs = [1, 2, 3, 4, 5];
    // pure
    xs.slice(0, 3);
    //=> [1, 2, 3]
    xs.slice(0, 3);
    //=> [1, 2, 3]
    xs.slice(0, 3);
    //=> [1, 2, 3]
    var xs = [1, 2, 3, 4, 5];
    // impure
    xs.splice(0, 3);
    //=> [1, 2, 3]
    xs.splice(0, 3);
    //=> [4, 5]
    xs.splice(0, 3);
    //=> []

    View Slide

  19. // impure
    var minimum = 21;
    function checkAge(age) {
    return age >= minimum;
    };
    // pure
    function checkAge(age) {
    var minimum = 21;
    return age >= minimum;
    };

    View Slide

  20. Side
    Effects

    View Slide

  21. Exemplo de side effects...
    ● mudança no sistema de arquivos
    ● inserção de registro no banco de dados
    ● fazer uma chamada HTTP
    ● mutations
    ● imprimir alguma informação na tela / logging
    ● obtenção de input do usuário
    ● querying o DOM (querySelector)

    View Slide

  22. Funções Puras: vantagens
    1. Cachelable;
    2. Portable;
    3. Testable;
    4. Referential Transparency;
    5. Parallel Code.

    View Slide

  23. Como saber se minha
    função é pura?
    Retornam o mesmo valor dado o mesmo input?
    Não faz alterações fora do escopo dela?
    Consigo usar em outro programa sem alterá-la?

    View Slide

  24. Imperativa
    vs
    Declarativa

    View Slide

  25. Imperativa
    1. Deixe o feijão de molho
    2. Bata no liquidificador
    3. Acrescente a cebola e sal
    4. Bata no liquidificador novamente
    5. Transfira para uma tigela
    6. Mexa com a colher até dobrar de volume
    7. Frite no azeite de dendê
    8. Retire o bolinho

    View Slide

  26. Declarativa
    tigela = liquidificar(acrescente(liquidificar(feijao), [cebola, sal])
    retirar fritar(fazer_bolinho(mexa_ate_dobrar(tigela)))

    View Slide

  27. // imperative
    var makes = [];
    for (var i = 0; i < cars.length; i++) {
    makes.push(cars[i].make);
    }
    // declarative
    var makes = cars.map(function(car) { return car.make; });

    View Slide

  28. JavaScript
    sofreu influências

    View Slide

  29. First Class
    Functions

    View Slide

  30. var hi = function(name) {
    return 'Hi ' + name;
    };
    var greeting = function(name) {
    return hi(name);
    };

    View Slide

  31. var greeting = hi;
    greeting('JSday');
    // "Hi JSday”

    View Slide

  32. var BlogController = (function() {
    var index = function(posts) {
    return Views.index(posts);
    };
    var show = function(post) {
    return Views.show(post);
    };
    var create = function(attrs) {
    return Db.create(attrs);
    };
    var update = function(post, attrs) {
    return Db.update(post, attrs);
    };
    var destroy = function(post) {
    return Db.destroy(post);
    };
    return {
    index: index,
    show: show,
    create: create,
    update: update,
    destroy: destroy,
    };
    })();
    var BlogController = {
    index: Views.index,
    show: Views.show,
    create: Db.create,
    update: Db.update,
    destroy: Db.destroy,
    };

    View Slide

  33. Higher-Order
    Functions

    View Slide

  34. function apply(fn, x) {
    return fn(x);
    }
    apply(function(x) {
    return x * 2;
    }, 10);
    //=> 20

    View Slide

  35. var calculadora = function (fn, x, y) {
    return fn(x, y);
    }
    var soma = function(x, y) { return x + y }
    var mult = function (x, y) { return x * y }
    calculadora(soma, 2, 2); // 4
    calculadora(mult, 5, 10); // 50
    ES5

    View Slide

  36. var getServerStuff = function(callback) {
    return ajaxCall(function(json) {
    return callback(json);
    });
    };
    // or
    var getServerStuff = ajaxCall;

    View Slide

  37. var getServerStuff = function(callback) {
    return ajaxCall(function(json) {
    return callback(json);
    });
    };
    // or
    var getServerStuff = ajaxCall;
    return ajaxCall(callback);

    View Slide

  38. var getServerStuff = function(callback) {
    return callback(json);
    };
    // or
    var getServerStuff = ajaxCall;

    View Slide

  39. $("#btn").click(function () {
    facaAlgumaCoisa();
    });
    ES5

    View Slide

  40. var app = angular.module('app');
    app.controller('MyController', function () {
    /* */
    });
    ES5

    View Slide

  41. Currying

    View Slide

  42. var greeting = function(greet, name) {
    return greet + ' ' + name;
    }
    greeting('Hello', 'World');
    // Hello World

    View Slide

  43. var greeting = function (greet) {
    return function (name) {
    return greet + ' ' + name;
    }
    }
    greeting('Hello')('World'); // Hello World

    View Slide

  44. var hello = greeting('Hello');
    hello('World'); // Hello World
    hello('John Doe'); // Hello John Doe

    View Slide

  45. Compose

    View Slide

  46. var compose = function(f, g) {
    return function(x) {
    return f(g(x));
    };
    };
    Representação matemática:
    (f º g)(x)

    View Slide

  47. var toUpperCase = function(x) {
    return x.toUpperCase();
    };
    var exclaim = function(x) {
    return x + '!';
    };
    var shout = compose(exclaim, toUpperCase);
    shout("send in the clowns");
    //=> "SEND IN THE CLOWNS!"

    View Slide

  48. // without compose
    var shout = function(x) {
    return exclaim(toUpperCase(x));
    };
    // with compose
    var shout = compose(exclaim, toUpperCase);
    shout("send in the clowns");
    //=> "SEND IN THE CLOWNS!"

    View Slide

  49. View Slide

  50. var g = function(x) {
    return x.length;
    };
    var f = function(x) {
    return x === 4;
    };
    var isFourLetterWord = compose(f, g);
    isFourLetterWord('four');
    //=> true

    View Slide

  51. Pointfree

    View Slide

  52. // não é pointfree pq mencionou o dado: word
    var snakeCase = function(word) {
    return word.toLowerCase().replace(/\s+/ig, '_');
    };
    // pointfree
    var snakeCase = compose(replace(/\s+/ig, '_'), toLowerCase);

    View Slide

  53. Declarative
    Coding

    View Slide

  54. // imperative
    var authenticate = function(form) {
    var user = toUser(form);
    return logIn(user);
    };
    // declarative
    var authenticate = compose(logIn, toUser);

    View Slide

  55. E o nosso acarajé, como
    seria em Pointfree?

    View Slide

  56. var liquidificar_tudo = compose(liquidificar, acrescente([cebola,
    sal]), liquidificar);
    var fazer_acaraje = compose(fritar, fazer_bolinho, mexa_ate_dobrar,
    liquidificar_tudo);
    fazer_acaraje(feijao);

    View Slide

  57. E depois?

    View Slide

  58. Futuro
    ● Hindley-Milner
    ● Functors
    ● Monoids and Monads
    ● Metaphors
    ● Programação Reativa
    ● etc...

    View Slide

  59. Ferramentas

    View Slide

  60. View Slide

  61. https://drboolean.gitbooks.io/mostly-adequate-guide

    View Slide

  62. Às vezes a implementação mais
    elegante é uma função.
    Não é um método.
    Não é uma classe.
    Não é um framework.
    É apenas uma função.
    -- John Carmack

    View Slide

  63. Obrigado!

    View Slide

  64. Referências
    ● https://medium.com/@matheusml/entendendo-programa%C3%A7%C3%A3o
    -funcional-em-javascript-de-uma-vez-c676489be08b#.vch1in9me
    ● https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a
    -pure-function-d1c076bec976#.t9t5iar42
    ● https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional
    ● https://www.sitepoint.com/introduction-functional-javascript/
    ● http://c2.com/cgi/wiki?ImmutableObjectsAndGarbageCollection

    View Slide