Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ernestweems/c97d3b4edc5090846da2 to your computer and use it in GitHub Desktop.
Save ernestweems/c97d3b4edc5090846da2 to your computer and use it in GitHub Desktop.

Revisions

  1. @mrkd mrkd created this gist Dec 3, 2015.
    78 changes: 78 additions & 0 deletions js-good-parts-fun-with-functions.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    <html><body><pre><script>
    "use strict";
    function log(arg) {
    document.writeln(arg);
    }

    function identity(x) {
    return x;
    }
    log(identity(3));

    function add(x, y) {
    return x + y;
    }
    function mul(x,y) {
    return x * y;
    }
    function sub(x,y) {
    return x - y;
    }


    log("add: " + add(2,2));
    log("mul: " + mul(2,4));
    log("sub: " + sub(2,2));


    // Write a function that takes an argument and returns a
    // function that returns that argument.
    function identityf(argument) {
    return function () {
    return argument;
    }
    }

    var three = identityf(3);

    log("identityf: " + three());

    // Write a function that adds from two invocations.
    function addf(first) {
    return function(second) {
    return first + second;
    }
    }

    log("addf: " + addf(3)(4));

    // Write a function liftf that takes a binary function, and
    // makes it callable with two invocations
    function liftf(binary) {
    return function(first) {
    return function(second) {
    return binary(first,second);
    }
    }
    }

    var addf = liftf(add);
    log("liftf: " + addf(3)(4));


    // function curry
    function curry(binary, first) {
    return function(second) {
    return binary(first, second);
    }
    }

    var add3 = curry(add, 3);
    log("curry: " + add3(4));
    log("curry(mul, 5)(6): " + curry(mul, 5)(6));





    </script></pre></body></html>