问题
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?
回答1:
s.map{ e => if(f(e)) transform(e) else e }
回答2:
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
来源:https://stackoverflow.com/questions/51001759/replace-elements-in-list-by-condition