I’m starting to study the Scala programming language.
I’ve some grasp of FP languages like Erlang and Haskell and I have a doubt about the meaning of the for/yield expression, like:
for (arg <- args) yield arg.length
This would collect an array with the lengths of any input argument.
From what I’ve understood this seems like the map function in normal FP programming:
map (\a -> a * 2) [1, 2, 3] (in Haskell)
I know that Scala library contains the scala.collection.map method, so I would like to know: is there any difference or limitation in using either style, or they are exactly the same?
for ... yieldcomprehension in Scala is translated by compiler to themap,flatMapandwithFiltermethod calls.forwithoutyieldwould be translated to theforeachmethod call. You can find some examples and more information here:http://tataryn.net/2011/10/whats-in-a-scala-for-comprehension/
and here
http://adamwojtuniak.wordpress.com/2010/09/24/scala-for-comprehensions/