0

I'm trying to find a concise way of passing the result of zipping two arrays into a map function, ie. one that does not require declaring both the input variables and using a fat arrow in the lambda.

This may not even be possible, but I thought I'd ask before giving up.

The first example is working code that prints the result of adding both arrays element-wise. The lambda for the zip has to declare x and y before they can be used.

The second example is non-compiling code which illustrates what I would like to do using "_" or similar to give the transformation function better usability for zipped inputs.

Example 1

object Example extends App {

  val numbers1: Array[Int] = Array(1,2,3,4,5)
  val numbers2: Array[Int] = Array(9,8,7,6,5)

  val result = (numbers1, numbers2).zipped.map( (x,y) => sum(x,y) )

  result.foreach( println(_) )

  def sum(x: Int, y: Int): Int = {
    x+y
  }
}

This is fine when the transformation function has a short name like "sum" and the input arrays are of primitives, but things get more verbose when passing in an array of wrapper objects which contain several member variables the transformation requires as arguments.

Is there a syntactic sugar which allows something like this: ?

Example 2

object Example extends App {

  val numbers1: Array[Int] = Array(1,2,3,4,5)
  val numbers2: Array[Int] = Array(9,8,7,6,5)

  val result = (numbers1, numbers2).zipped.map( sum(_) )

  result.foreach( println(_) )

  def sum( inputTuple: (Int, Int) ): Int = {
    val x = inputTuple._1
    val y = inputTuple._2
    x + y
  }
}

The more I detail this the more I feel like I've written myself into code smell, so if thats the answer please say so and I'll go solve the problem from another direction.

1

1 Answer 1

4

You can just...

val result = (numbers1, numbers2).zipped.map(sum)

... or even slicker ...

val result = numbers1 zip numbers2 map sum

It's also worth noting that this format allows for a more natural argument list in the sum() method.

def sum(x:Int, y: Int): Int = x + y
Sign up to request clarification or add additional context in comments.

3 Comments

The mismatched types was an error on my part. I've corrected my post to reflect.
Your previous edit was perfect haha, why did you remove it? :)
I had gotten a bit off with what map was sending to sum. Tupling not required.

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.