Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent in Scala to Python's more general map function?

I know that Scala's Lists have a map implementation with signature (f: (A) => B):List[B] and a foreach implementation with signature (f: (A) => Unit):Unit but I'm looking for something that accepts multiple iterables the same way that the Python map accepts multiple iterables.

I'm looking for something with a signature of (f: (A,B) => C, Iterable[A], Iterable[B] ):Iterable[C] or equivalent. Is there a library where this exists or a comparable way of doing similar?

Edit:

As suggested below I could do

val output = myList zip( otherList ) map( x => x(0) + x(1) )

but that creates a temporary list in between steps. If the commentor would post I could upvote him (hint, hint) but is there another way?

like image 289
wheaties Avatar asked Apr 16 '10 02:04

wheaties


1 Answers

In scala 2.8, there is a method called zipped in Tuple2 & Tuple3 which avoid to create temporary collection. Here is some sample use case:

Welcome to Scala version 2.8.0.r21561-b20100414020114 (Java HotSpot(TM) Client VM, Java 1.6.0_18).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val xs = 0 to 9
xs: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> val ys = List.range(0,10)
ys: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> val zs = Array.range(0,10)
zs: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> (xs,ys).zipped.map{ _+_ }
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)

scala> (zs,ys,xs).zipped.map{ _+_+_ }
res2: Array[Int] = Array(0, 3, 6, 9, 12, 15, 18, 21, 24, 27)

scala>

There is a zip method in both Tuple2 and Tuple3. xs.zip(ys) is the same as (xs,ys).zip

Note: There is also some shortage in (xs,ys).zip and (xs,ys).zipped, make sure that xs can't be a INFINITE Stream. Go to Ticket #2634 for more information. I have a post in nabble.com some days ago which shows my opinions about how to fix this ticket.

like image 102
Eastsun Avatar answered Oct 01 '22 08:10

Eastsun