Wednesday, April 10, 2013

scala yield vs map which is nicer?

currently I'm playing a bit more with scala in an attempt to leverage the power of my new pair of radeon 7970 for GPU calculations and I'm a touch unsure, which syntax I prefer and is easier to read.

example a:


scala> 1 to 10 map ( _ * 2)
res4: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)


versus example b:

scala> for (i <- 10="" 1="" 2="" i="" nbsp="" to="" yield="">
res5: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)


They both produce the same result, but I feel the b is easier to understand from a none scala perspective. But a. Is shorter and somewhat clearer

Now if we change this to:


scala> val result  = 1 to 10 map ( _ * 2)
result: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

and

scala> val result = for (i <- 10="" 1="" 2="" i="" nbsp="" to="" yield="">
result: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

now the first version seems to make a lot more sense and the second looks unwieldy complicated.

No comments:

Post a Comment