Skip to content
refractalize edited this page May 25, 2012 · 2 revisions

Comprehensions

Comprehensions are pretty handy at creating very tight and almost incomprehensable (pun intended?) algorithmic code. Used by Haskell hackers globally, they must be a good idea.

Where

We'll introduce the where macro, that has the following syntax:

(x * y) where (x = [1..2], (x) is even, y = [4, 5, 6], x * y > 10)

And would expand to:

function () {
    var results = [];
    var list = [1, 2];
    for (var x = 0; x < list.length; x++) {
        if (isEven(x)) {
            var pogo$1$y = [4, 5, 6];
            for (var y = 0; y < pogo$1$y.length; y++) {
                if (x * y > 10) {
                    results.push(x * y);
                }
            }
        }
    }
    return results;
}();

Comprehensions can take on most list processing use-cases:

  • each

      (console: log (x)) where (x = [1, 2])
    
  • map

      (y) where (x = [1, 2], y = x + 1)
    

    Or

      (x + 1) where (x = [1, 2])
    
  • filter

      (x) where (x = [1, 2], (x) is even)
    

Given

We'll also introduce the given macro, which is identical to the where macro, but the body is in a block, for example:

given (x = [1, 2], (x) is even)
    console: log (x)

Ranges

We can also allow ranges to be defined with the = operator:

(x) where (x = 5..10)
Clone this wiki locally