GithubHelp home page GithubHelp logo

functional.js's Introduction

functional.js

Functional Programming for JavaScript

// Lazy Evaluation
var th = new Thunk(() => {
    console.log("hello world");
    return 2 + 2;
});
th.value(); // => hello world, 4
th.value(); // => 4

// Sum Types
var Maybe = new Variant({
    Just: (value) => ({value}),
    Nothing: () => ({})
});
Maybe.pure = Maybe.Just;
Maybe.prototype.map = function(f) {
    return this.match({
        Just: (x) => Maybe.Just(f(x)),
        _: () => Maybe.Nothing()
    });
};
Maybe.pure(5).map(x => x + 1).value; // => 6

// Tail Recursion
function factorial(n) {
    var f = new TailRecursive(function(accu, n) {
        if(n == 0) return accu;
        else return this.tailcall(accu * n, n - 1);
    });
    return f.run(1, n);
}
factorial(5); // => 120

// Simple Product Types
var tup = new Tuple(1,2,3);
tup.unpack((x,y,z) => x+z); // => 4
tup.length; // => 3

// Pure Input/Output
var ioPrompt = m => new IO(() => prompt(m));
var ioAlert = m => new IO(() => alert(m));
var main =
    ioPrompt("enter your name").map(name => "hello " + name).bind(ioAlert);
IO.pure("hello world").bind(ioAlert).execute(); // => hello world

functional.js's People

Contributors

ac12353 avatar marijaninjo avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.