gpt4 book ai didi

scala - Scala中同时打印和返回值的惯用方式

转载 作者:行者123 更新时间:2023-12-01 09:20:36 26 4
gpt4 key购买 nike

在 Scala 中打印(或做任何我需要做的事情)和返回值的惯用方式是什么?例如,

Seq(1,2,3)
.map(_ * 2)
.xxx(println) // Here I want to print the intermediate sequence
.foldLeft(0)(_ + _)

我能想到的一种方法是使用隐式,但我不太喜欢自己修补标准库。

注意

在 Ruby 中我们可以使用 Object#tap

[1,2,3]
.map { |i| i * 2 }
.tap { |i| puts i }
.reduce(0) { |x, i| x += i }

最佳答案

Object#tap在 Ruby 中基本上是 K 组合器的变体。我不相信 Scala 标准库中有实现,但很容易添加自己的:

implicit class TapExtension[T](o: => T) {
def tap(f: T => Unit) = { f(o); o }
}

注意:这是一个隐式转换,它不是猴子补丁。

然后,你可以这样使用它:

Seq(1,2,3)
.map(_ * 2)
.tap(println)
.foldLeft(0)(_ + _)

关于scala - Scala中同时打印和返回值的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com