user_123945839432
user_123945839432

Reputation: 189

map function in Scala clarification

I am confused on how to write the map function, which maps over two lists:

for example:

def map[A,B,C](f: (A, B) => C, lst1: List[A], lst2: List[B]): List[C]

The input would be 2 lists and the output could be a list that adds the integers alternatively

Test example:

assert(map(add, List(1, 2, 3), List(4, 5, 6)) == List(5, 7, 9))

Upvotes: 1

Views: 86

Answers (2)

triggerNZ
triggerNZ

Reputation: 4751

As stated in m-z's answer you can zip the lists, and then map on the list of tuples. If you want to avoid the use of tupled, you can do the destructure explicitly:

def map[A,B,C](f: (A, B) => C, lst1: List[A], lst2: List[B]): List[C] = {
  val zipped = lst1 zip lst2
  zipped.map { case (a,b) => f(a,b) }
}

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

You could use f.tupled to convert f from a function that accepts to arguments (A, B) => C, to a function that accepts one argument as a tuple ((A, B)) => C. Then, you can zip the lists together (make them one list of tuples) and feed them to f using the traditional map.

def map[A,B,C](f: (A, B) => C, lst1: List[A], lst2: List[B]): List[C] = 
   (lst1 zip lst2) map f.tupled

scala> def add(a: Int, b: Int): Int = a + b
add: (a: Int, b: Int)Int

scala> map(add, List(1, 2, 3), List(4, 5, 6))
res20: List[Int] = List(5, 7, 9)

Keep in mind that if the two lists are not the same size, then zip will truncate the longer list to match the size of the smaller one.

Upvotes: 5

Related Questions