ZhongBot
ZhongBot

Reputation: 129

Scala - map function to replace negatives with previous number in list

I have a list of numbers

[1, 2, 3, -1000, 4, -1000]

I want to write a map function to replace all negative numbers in my list with the previous number (before the negative)

In this case the output will be

[1, 2, 3, 3, 4, 4]

What is the best way to write this map function?

Upvotes: 3

Views: 209

Answers (2)

Lodewijk Bogaards
Lodewijk Bogaards

Reputation: 19987

yourList.foldLeft(List[Int]()) { (acc, i) => if (i >= 0) i :: acc else acc.head :: acc }.reverse

will throw an exception if first number is negative.

With thanks to Aivean.

Upvotes: 4

kes
kes

Reputation: 6177

def replaceNegatives(list: List[Int], prev: Int = 0): List[Int] = {
   list match {
     case Nil => Nil
     case (x :: xs) if x < 0 => prev :: replaceNegatives(xs, prev)
     case x :: xs => x :: replaceNegatives(xs, x)
   }
}

Example:

scala> replaceNegatives(List(1, 2, 3, -1000, 4, -1000))
res1: List[Int] = List(1, 2, 3, 3, 4, 4)

The second argument (prev) is optional; it is the default value to use if the first item in the list is negative.

Upvotes: 1

Related Questions