按条件替换列表中的元素

编程入门 行业动态 更新时间:2024-10-28 00:18:53
本文介绍了按条件替换列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个很大的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).

我看着cats-mtl FunctorEmpty (坚持使用函数式编程风格),但在我看来,它似乎不起作用.也许某些cats/scalaz数据结构在这里有用吗?还是其他方式?

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 }

更多推荐

按条件替换列表中的元素

本文发布于:2023-11-10 15:42:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575779.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   条件   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!