Search code examples
scalalistfunctional-programmingscalazscala-cats

Replace elements in List by condition


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?


Solution

  • s.map{ e => if(f(e)) transform(e) else e }