0

I want to apply a simple anonymous function to every element in a Array[Array], and output a Array[Array]. This function basically convert all positive numbers into 1, all negatives -1.

I know how to do the same thing for Array, but not Array[Array]. Is there a way to unwrap it?

val data = Array(Array(1,2),Array(-1,-2))
data.map(x => x.map{if (y > 0.0) 1.0 else 0.0})
2
  • 1
    Your code doesn't compile, you need a y => before the if. Apart from that it should work fine. Commented Mar 3, 2018 at 23:53
  • I'm not very familiar with Scala, but you can in general compose a map function with itself to give you map2, which behaves as you require. Commented Mar 4, 2018 at 0:12

1 Answer 1

4

first map would give you each Array[T], second map would give you each element in that array.

given,

scala> val data = Array(Array(1,2),Array(-1,-2))
data: Array[Array[Int]] = Array(Array(1, 2), Array(-1, -2))

here's how you can apply function on each elem of second array,

scala> data.map(_.map(elem => if (elem > 0) 1 else -1 ))
res0: Array[Array[Int]] = Array(Array(1, 1), Array(-1, -1))

You can also use collect,

scala> data.map(_.collect{case elem if elem > 0 => 1 case _ => -1 })
res1: Array[Array[Int]] = Array(Array(1, 1), Array(-1, -1))

To simplify the same work using a function,

scala> def plusOneMinusOne(x: Int) = if (x > 0) 1 else -1
plusOneMinusOne: (x: Int)Int

scala> data.map(_.map(plusOneMinusOne)) 
res3: Array[Array[Int]] = Array(Array(1, 1), Array(-1, -1))
Sign up to request clarification or add additional context in comments.

Comments

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.