Replace elements in List by condition

假装没事ソ 提交于 2019-12-08 12:29:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!