Giter VIP home page Giter VIP logo

burrido's Introduction

burrido Build Status

An experiment in bringing Haskell's programmable semicolon to JavaScript, using generators.

Installation

npm install --save burrido

Usage

import Monad from 'burrido'

const ArrayMonad = Monad({
  pure: x => [x],
  bind: (xs, f) => xs.map(f).reduce((a, b) => a.concat(b), [])
})

ArrayMonad.Do(function*() {
  const x = yield [1,2]
  const y = yield [3,4]
  return x * y
}) // -> [3,4,6,8]

The above should look fairly self-explanatory to a Haskell programmer: we are declaring a Monad instance for arrays, which requires us to define two functions: pure and bind. Then we obtain a special function Do which is a do-notation tailored to that particular monad. We pass a generator function to Do, within which we gain access to the yield keyword, allowing us to "unwrap" monadic values and release their effects.

In fact this is a bit more versatile than Haskell's do-notation in a couple of interesting ways:

  1. Haskell's Monad is a type class, which means that there can only be one way in which a given type constructor is considered a monad within a given scope. But some type constructors can be considered monadic in more than one way (e.g. Either). By contrast, here you can create as many Monad definitions as you want for a particular type (constructor), and each just has its own special Do function.
  2. While
const foo = yield bar

is comparable to

foo <- bar

in do-notation, one can also create compound yield expressions which have no direct analogue in Haskell. For example,

const foo = yield (yield bar)

would have to be written as

foo' <- bar
foo <- foo'

in do-notation. In the context of Do blocks, yield serves a similar purpose to the ! operator in both Idris and the Effectful library for Scala.

An example using RxJS

RxJS Observables form a monad in several different ways:

const { just: pure } = Observable

const { Do: doConcat } = Monad({
  pure,
  bind: (x, f) => x.concatMap(f)
})

const { Do: doMerge } = Monad({
  pure,
  bind: (x, f) => x.flatMap(f)
})

const { Do: doLatest } = Monad({
  pure,
  bind: (x, f) => x.flatMapLatest(f)
})

It's instructive to see what happens when you apply these different do-notations to the same generator block:

const { from } = Observable

const block = function*() {
  // for each x in [1,2,3]...
  const x = yield from([1,2,3])
  // wait 1 second
  yield pure({}).delay(1000)
  // then return the value
  return x
}

// Prints 1, 2, and 3 separated by 1 second intervals
doConcat(block).subscribe(console.log)
// Waits 1 second and then prints 1, 2, 3 all at once
doMerge(block).subscribe(console.log)
// Waits 1 second and then prints 3
doLatest(block).subscribe(console.log)

This should make sense if you think about the semantics of each of these different methods of "flattening" nested Observables. Each do* flavor applies its own semantics to the provided block, but they all return Observables, so we can freely combine them:

doConcat(function*() {
  const x = yield doConcat(function*() {
          //...
        }),
        y = yield doMerge(function*() {
          //...
        }),
        z = yield doLatest(function*() {
          //...
        })
  return { x, y, z }
})

RxJS has a function spawn which allows you to use this kind of syntax with Observables, but it only works properly with single-valued streams (essentially Promises), whereas burrido allows manipulating streams of multiple values, using multiple different semantics.

Caveats

Because JavaScript's generators are neither immutable nor cloneable, we are forced to simulate immutable generators using a library called immutagen. There are two unavoidable downsides to this approach:

  • pure and bind must be side-effect free. This can always be achieved in practice by making the monadic type lazy (wrapping it in a closure). See this issue.
  • The simulation is inefficient, requiring O(n^2) steps to execute the nth yield within a single generator. See this issue.

With natively immutable generators (or the native ability to clone mutable generators), both of these limitations would go away.

burrido's People

Contributors

pelotom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

burrido's Issues

Complexity of current implementation is too high

@safareli commented on Wed Feb 01 2017

Doing concat on normal js Array has quadratic complexity, plus doing map on the history is linear.
So I belive complexity this far is O(n^2 + n). but this is for nth yield, if i'm correct, using this for some program With n yield, will have complexity of O(n * (n^2 + n)) i.e. O(n^3+n^2). and I think this should be at least noted in readme.

btw the O(n^2 + n) part could be optimised to O(n) by using some some sequence structure which has constant time push (as you push one element only), you could even use normal Lined list for it (List = Nil | Cons a (List a)). this way complexity for some program With n yield will be O(n * n) i.e. O(n^2).


@pelotom commented on Wed Feb 01 2017

Doing concat on normal js Array has quadratic complexity,

Hm, I don't think you're right about that. Concatenating 2 arrays of length n and m would be O(n + m), but appending a single element to the end of an array, as we're doing here, is just O(n). Using a cons-list for the history would make appending an element constant time, but because of the map the overall complexity of a single yield would remain O(n).


@safareli commented on Wed Feb 01 2017

Correct, so concat will be O(n) + map O(n) so single yield will stay O(n), i.e. we can't fix it.

But I still think that, it should be noted in readme, as users of immutagen and burrido might not be aware of this.


@pelotom commented on Wed Feb 01 2017

Quoting from the current README:

Note also that there is inherent inefficiency in this technique, because every yield expression requires replaying the entire history up to that point. For this reason it's advisable to keep expensive computations to a minimum inside immutable generators, particularly as the number of yield expressions in the generator grows. Even if there isn't a lot of expensive computation, the runtime complexity will be quadratic in the number of yield expressions to be evaluated, so be careful.

Is that not sufficiently clear?


@safareli commented on Wed Feb 01 2017

didn't saw that in "burrido"


@pelotom commented on Wed Feb 01 2017

I'd be happy to review a PR on the burrido repo that adds wording to that effect.

Modeling applicative do

This is really nice, but one thing it leaves to be desired is the ability to applicatively do over independent stages. E.g. if I have:

const t = Fluture.delay(1000).map(_ => 1)
const x = yield t;
const y = yield t;
return x + y

Neither of the expressions bound to x and y are dependent on each other; thus we can use t.map(x => y => x + y).ap(t) rather than t.chain(x => t.chain(y => x + y)), resulting in the whole thing finishing in 1 second rather than 2. In Haskell (which obviously doesn't have to work under the same constraints as this library), do notation now desugars to the former rather than the latter where possible.

I can't see a way of modeling this with generators, thought maybe you might have some ideas.

Typescript definitions

Not an issue per se, I was trying to do the same proof of concept as you did, but for TypeScript.

Wondering how could the generators work so well for Promises (async/await in TS transpiles into generators), but not for any object that has map/flatmap methods. So I encountered the need for cloneable generators, and when googled it, found your project!

Have you ever tried to check if this could work with types?

this works well only for small subset of effects for monads like rx observable

Here is a pretty typical and simple example, say, we need to update DB before some further actions, this is HTTP POST running using promises. Promises may be turned into observable, and JS has no its own side effects:

doMerge(function*() {
  const m = yield fromPromise(updateDb())
  const x = yield from([1,2])
  return `${x} ${m}`
}).subscribe(function(res) {
  console.log(res)
})

This updates DB 4 times!

More details in this gist.
And it is even theoretically not possible, arbitrary monad requires first class continuations, just coroutines are not enough.

There is in fact my tools (sorry for promoting it in this issue, but I suppose it may be interesting) may use same generators syntax for arbitrary monad.

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.