documentcloud / underscore-contrib

The brass buckles on Underscore's utility belt
MIT License
621 stars 118 forks source link

Include support for monads and other execution abstractions? #9

Open raganwald opened 11 years ago

raganwald commented 11 years ago

One option is to conform to the Fantasy Land 'standard' interface.

fogus commented 11 years ago

I think the answer is probably 'yes' on the addition question and to the fantasy land interface. However, there are a few things that are unclear to me even still:

raganwald commented 11 years ago

My uneducated perspective: Monads, Functors, and Applicative Functors are, from a JS-point-of-view, design patterns. Fantasy Land is a loose interface for same.

The direction I've been experimenting with:

  1. _.pipeline is the optimized way to chain functions without decoration. It has no options.
  2. _.sequence is a template function that accepts an object (with properties inherited from a prototype if the programmer prefers) and one or more functions to chain.

e.g.

var Maybe = {
  chain: function maybe (value, fn) {
    return _.existy(value) ? fn(value) : value;
  }
}

_sequence(Maybe, fn1, fn2, fn3)(seed)
  //=> result

With this implementation, _sequence({}, fn1, fn2, ...) has the same semantics as _.pipeline.

It is then possible to put functions like _.maybe(...) and _.list(...) in the library for ease of use. They delegate to _.sequence.

I have implementations of _.sequence(Callback, ...) and _.sequence(Then) working for chaining async via callbacks and promises, as well as transformers so that you can mix callback and promise code in the same sequence.

puffnfresh commented 11 years ago

I dislike the term "design patterns" since structures from abstract algebra generally lack "design"; they're directly derived from common mathematical structures.

Anyway, is underscore-contrib going to provide functional data and control structures? If so, I'd love for them to be Fantasy Land compatible.

Otherwise, we can still supply some useful functions which work for the structures. My Fantasy Sorcery project has a few:

The join and lifting functions work for all Fantasy Land compatible monads and applicatives, respectively. There's many more we can derive but that's as far as I got :smile:

raganwald commented 11 years ago

I dislike the term "design patterns" since structures from abstract algebra generally lack "design"; they're directly derived from common mathematical structures.

I agree with this, however I worry that in JS we are severely limited in expressiveness. We cannot, to my knowledge, enforce some of the necessary constraints/contracts required. So I'm leery of saying "X is a Monad" and lean towards, "X is a design pattern that, amongst other things, can implement a Monad." I am open to being more rigorous.

raganwald commented 11 years ago

But yes, Monads are not design patterns. Agree 100%.