0

I've tried to use zipped method for tuple to browse temporary zipped list

give it be something like it:

val l1 : List[Int] = List(1,2,3)
val l2 : List[Int] = List(2,3,1)
val l3 : List[Int] = for ( (a,b) <- (l1,l2).zipped ) yield a+b

It is a synthetic example and may be replaced with just map function, but I want to use it in more complicated for expressions.

It gives me error: wrong number of parameters; expected = 2 which make sense since (l1,l2).zipped.map has two arguments. What is the right way to translate two-argument map function inside for comprehension?

0

2 Answers 2

1

You cannot translate the zipped version into a for statement because the for is just

(l1,l2).zipped.map{ _ match { case (a,b) => a+b } }

and zipped's map requires two arguments, not one. For doesn't know about maps that take two arguments, but it does know how to do matches. Tuples are exactly what you need to convert two arguments into one, and zip will create them for you:

for ((a,b) <- (l1 zip l2)) yield a+b

at the cost of creating an extra object every iteration. In many cases this won't matter; when it does, you're better off writing it out in full. Actually, you're probably better yet using Array, at least if primitives feature heavily, so you can avoid boxing, and work off of indices.

Sign up to request clarification or add additional context in comments.

Comments

1
scala> val l1 : List[Int] = List(1,2,3)
l1: List[Int] = List(1, 2, 3)

scala> val l2 : List[Int] = List(2,3,1)
l2: List[Int] = List(2, 3, 1)

scala> val l3 : List[Int] = for ( (a,b) <- (l1,l2).zip) yield a+b    
l3: List[Int] = List(3, 5, 4)

2 Comments

i think zipped function more efficiently, it doesn't create temporary collection.
and there is no way to embed it in a for comprehension, is it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.