We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Scala noob here, any comments if this is a valid solution
scala
def abs(x:Int):Int = {
if(x<0)
x * -1
else
x
}
def f(arr:List[Int]):List[Int] = {
arr.map(x=> abs(x)).toList
}

## Update List

You are viewing a single comment's thread. Return to all comments →

Scala noob here, any comments if this is a valid solution

`scala def abs(x:Int):Int = { if(x<0) x * -1 else x } def f(arr:List[Int]):List[Int] = { arr.map(x=> abs(x)).toList`

}

Instead of to declare abs function, you can use Math.abs, and also the .toList is not necessary because the map function returns in this case a List

Here is my solution

arr.map(Math.abs(_))

even better with arr.map(math.abs)

How about arr.map(_.abs)?

I think this is a good solution.

def f(arr:List[Int]):List[Int] = for(i <- arr) yield(i.abs)

My favorite :D Although my first answer was with "if (x<0) ..."