1

I tried to use zip and map to create zipwith function like:

def zipWithArray(f : (Int, Int) => Int)(xs : Array[Int], ys: Array[Int]) : Array[Int] = xs zip ys map f

But I got the following compile error:

type mismatch; found : (Int, Int) => Int required: ((Int, Int)) => ? 

I know the zip is (Array[Int], Array[Int])=>Array((Int, Int)), so the f should be (Int, Int) => Int and the total result is Array[Int]. Could anyone help to explain the case please. Thanks a lot.

3 Answers 3

3

(Int, Int) => Int is function which takes two Int as argument. ((Int, Int)) => ? is function which takes one tuple which consists of two Int as argument.

Since xs zip ys is array of tuple, what you need is function which takes tuple as argument and returns Int.

So xz zip ys map f.tupled should work.

Reference: How to apply a function to a tuple?

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

Comments

0

It's pretty much as the error message states; change your function signature to:

def zipWithArray(f : ((Int, Int)) => Int)(xs : Array[Int], ys: Array[Int]) 

Without the extra parentheses, f looks like a function that takes two integers, rather than a function that takes a tuple.

Comments

0

Convert the function to accept arguments as tuples and then map can be used to call the function. For example :

scala> def add(a : Int, b: Int) : Int = a + b add: (a: Int, b: Int)Int scala> val addTuple = add _ tupled <console>:12: warning: postfix operator tupled should be enabled by making the implicit value scala.language.postfixOps visible. This can be achieved by adding the import clause 'import scala.language.postfixOps' or by setting the compiler option -language:postfixOps. See the Scaladoc for value scala.language.postfixOps for a discussion why the feature should be explicitly enabled. val addTuple = add _ tupled ^ addTuple: ((Int, Int)) => Int = scala.Function2$$Lambda$224/1945604815@63f855b scala> val array = Array((1, 2), (3, 4), (5, 6)) array: Array[(Int, Int)] = Array((1,2), (3,4), (5,6)) scala> val addArray = array.map(addTuple) addArray: Array[Int] = Array(3, 7, 11) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.