0

I have a pretty much large val s: List[Int] = //..., a function f: Int => Boolean and a function transform: Int => Int.

The problem: I want to create another List[Int] such that all elements e: Int of the s: List[Int] such that f(e) = true are replaced with transform(e).

I looked at cats-mtl FunctorEmpty (to adhere to functional programming style), but it does not seem to work in my case. Maybe some cats/scalaz data structures can be useful here? Or any other way?

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
St.Antario
  • 26,175
  • 41
  • 130
  • 318

2 Answers2

6
s.map{ e => if(f(e)) transform(e) else e }
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
0

List(1, 2, 3).map(fn) creates a new list which might be not exactly want you need, especially if input is large.

Alternative solution would be to map on view List(1, 2, 3).view.map(...) without creating a new list and only "materialize" results when you need them

mibon
  • 295
  • 2
  • 9