按条件替换列表中的元素 [英] Replace elements in List by condition
本文介绍了按条件替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很大的val s: List[Int] = //...
,一个函数f: Int => Boolean
和一个函数transform: Int => Int
.
I have a pretty much large val s: List[Int] = //...
, a function f: Int => Boolean
and a function transform: Int => Int
.
问题 :我想创建另一个List[Int]
,以便将s: List[Int]
的所有元素e: 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?
推荐答案
s.map{ e => if(f(e)) transform(e) else e }
这篇关于按条件替换列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文