Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is 'yield' in Scala equivalent to map function?

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?

like image 390
Vincenzo Maggio Avatar asked Apr 16 '12 21:04

Vincenzo Maggio


1 Answers

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/

like image 98
tenshi Avatar answered Oct 24 '22 18:10

tenshi