Reputation: 3869
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?
Upvotes: 7
Views: 2054
Reputation: 26576
for ... yield
comprehension in Scala is translated by compiler to the map
, flatMap
and withFilter
method calls. for
without yield
would be translated to the foreach
method 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/
Upvotes: 15
Reputation: 7320
The for-yield is compiled down to maps - it is in the Programming in Scala book.
Upvotes: 3
Reputation: 3246
Scala's for
/yield
expressions are completely equivalent to list/monad comprehensions in Haskell, and have exactly the same capabilities, as long as you stick to one type per for
expression. (I don't know about Erlang, though.)
In particular, your example exactly translates to [length arg | arg <- args]
, translating the Scala method call x.f
to the Haskell function application f x
.
Upvotes: 6