列表中每个元素的链条

发布于 2025-02-13 10:36:45 字数 218 浏览 0 评论 0原文

是否存在列表中每个元素上调用功能的优雅方式与接下来的接合?

例如,我有:

val list = listOf(1,5,3,4)
fun Int.foo(next: Int) = //some logic

我想生成此表达式:

val result = 1.foo(5).foo(3).foo(4)

Is exist elegant way to call function on every element in list to tie with next till the end?

For example I have:

val list = listOf(1,5,3,4)
fun Int.foo(next: Int) = //some logic

I want to generate this expression:

val result = 1.foo(5).foo(3).foo(4)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2025-02-20 10:36:45

此类操作称为降低折叠收集,并使用 redion()

list.reduce(Int::foo)

例如:

1.plus(5).plus(3).plus(4) // 13
listOf(1, 5, 3, 4).reduce(Int::plus) // 13

Such operation is called reducing or folding a collection and is done using reduce():

list.reduce(Int::foo)

For example:

1.plus(5).plus(3).plus(4) // 13
listOf(1, 5, 3, 4).reduce(Int::plus) // 13
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文