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

Transcript

64 slides
  1. O que é uma função? É uma relação* entre um

    input e um output. -- mathsisfun.com
  2. 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); //=> []
  3. // impure var minimum = 21; function checkAge(age) { return

    age >= minimum; }; // pure function checkAge(age) { var minimum = 21; return age >= minimum; };
  4. 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)
  5. 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?
  6. 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
  7. // 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; });
  8. var hi = function(name) { return 'Hi ' + name;

    }; var greeting = function(name) { return hi(name); };
  9. 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, };
  10. 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
  11. var getServerStuff = function(callback) { return ajaxCall(function(json) { return callback(json);

    }); }; // or var getServerStuff = ajaxCall; return ajaxCall(callback);
  12. var greeting = function(greet, name) { return greet + '

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

    return greet + ' ' + name; } } greeting('Hello')('World'); // Hello World
  14. var compose = function(f, g) { return function(x) { return

    f(g(x)); }; }; Representação matemática: (f º g)(x)
  15. 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!"
  16. // 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!"
  17. var g = function(x) { return x.length; }; var f

    = function(x) { return x === 4; }; var isFourLetterWord = compose(f, g); isFourLetterWord('four'); //=> true
  18. // 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);
  19. // imperative var authenticate = function(form) { var user =

    toUser(form); return logIn(user); }; // declarative var authenticate = compose(logIn, toUser);
  20. var liquidificar_tudo = compose(liquidificar, acrescente([cebola, sal]), liquidificar); var fazer_acaraje =

    compose(fritar, fazer_bolinho, mexa_ate_dobrar, liquidificar_tudo); fazer_acaraje(feijao);
  21. Futuro • Hindley-Milner • Functors • Monoids and Monads •

    Metaphors • Programação Reativa • etc...
  22. À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

More Decks by Jonata Weber

Other Decks in Technology