Monday, 1 September 2014

Scala Note 26: For-Comprehension v.s For-Loop


1. A for-comprehension is of the form

for ( s ) yield e

Here, s is a sequence of generators, definitions and filters. A generator is of the form
val x <e, where e is a list-valued expression. It binds x to successive values in the
list. The sequence s starts in each case with a generator. If there are several generators in a sequence, later generators vary more rapidly than earlier ones.
A definition is of the formval x = e. It introduces x as a name for the value of e in the rest of the comprehension. 
A filter is an expression f of type Boolean. It omits from consideration all bindings for which f is false

2. map and flatMap
Every for-comprehension can be expressed in terms of the three higher-order functions

map, flatMap and filter.

for (x <-e) yield e’
        is translated to:

e.map(x => e’)

applies a transformation of the monad "content" mantaining the monad "external shape"  
i.e. a List remains a List and an Option remains an Option but the inner type changes

for (x <-e; y <-e’; s) yield e’’
  where s is a (possibly empty) sequence of generators or filters is translated to
e.flatMap(x => for (y <-e’; s) yield e’’)

applies a transformation of the monad "content" by composing
this monad with an operation resulting in another monad instance of the same type

3, For-Loop

for ( s ) e

This construct is the same as the standard for-comprehension syntax except that
the keyword yield is missing. The for-loop is executed by executing the expression

e for each element generated fromthe sequence of generators and filters s.



Reference:
http://stackoverflow.com/questions/14598990/confused-with-the-for-comprehension-to-flatmap-map-transformation



No comments:

Post a Comment