0
votes

I am trying to combine lists with the following functions:

def merge(first: List[(Char, Int)], other: List[(Char, Int)]): List[List[(Char, Int)]] = 
  first.flatMap(tpl => other map (tpl2 => List(tpl, tpl2)))

def combine(l: List[List[(Char, Int)]]): List[List[(Char, Int)]] = l reduceLeft merge

Unfortunately, I get the following compiler message:

Error: type mismatch;
found: (List[(Char, Int)], List[(Char, Int)]) => List[List[(Char, Int)]]
required: (List[Product with java.io.Serializable], List[(Char, Int)]) => List[Product with java.io.Serializable]
l reduceLeft merge

I understand that reducing a List[Int] can only generate a result of Int. In my case, I have List[List[(Char, Int)]] so I expect that I can generate a result of List[(Char, Int)]. Can anybody help me understand what is wrong with my code?

1
You're mapping over other and adding tpl to all elements of the other list of tuples? - Yuval Itzchakov
yes I am so that if first = List(('a',1)) and other = List(('b',1), ('b',2)) it would return List(List(('a',1),('b',1)), List(('a',1),('b',2))) - Tundebabzy

1 Answers

1
votes

Definition of reduceLeft:

def reduceLeft[B >: A](op: (B, A) ⇒ B): B

So your function merge must return List[(Char, Int)] not List[List[(Char, Int)]] . Also your function combine will return List[(Char, Int)] as it reduces List inside List.