Introduction, comprehensions beyond arrays

Mike Stay metaweta at gmail.com
Thu May 9 21:42:23 PDT 2013


My name is Mike Stay; I was a principal developer on Caja and worked
with Mark Miller on designing the security features that he worked to
get into ES5.  I've looked through the archive for stuff on array
comprehensions and didn't see any discussion about the following
point, but I could easily have missed it.

In Scala, "for comprehensions" look roughly like this:
  for ( x <- expr1; y <- expr2(x); ... ; z <- exprN(x, y, ...) ) {
    yield (result(x, y, ..., z))
  }
which in ES harmony would look like
  [result(x, y, ..., z) for (x of expr1) for (y of expr2(x)) ... for
(z of exprN(x, y, ...))]

In Scala, this is desugared into
  expr1.flatMap(x =>
    expr2(x).flatMap(y => ...
      exprN(x, y, ...).map(z =>
        result(x, y, ..., z)
      )
    )
  )
[Note the final method is map(), not flatMap().]

For arrays, flatMap is map followed by flatten, which concatenates a
list of lists into a single list.  This is a relatively simple
transformation that would grant a lot of power, while not changing
anything (so far as I can tell) about the current semantics.  It
enables a programmer to use the same syntax for any monad, so pick
your favorite: promises, membranes, parsers, chaining UI actions, etc.

For example,
    [JSON.parse(x) for (x of fetch("http://example.com/myData"))]
could be a promise for the result of an asynchronous fetch, much like Q.when().

Chaining user events is easy:
    [ menuItem.display() for (pos of MouseClick()) for (menuItem of
MenuItem(pos)) ]

etc.
-- 
Mike Stay - metaweta at gmail.com
http://www.cs.auckland.ac.nz/~mike
http://reperiendi.wordpress.com


More information about the es-discuss mailing list