问题描述
在Scala中,当我有这个表达式时
In Scala, when I have this expression
f1 ( f2 ( f3 (p)))
有没有办法我可以使用类似
Is there a way that I can use something like in
F#
p |> f3 |> f2 |> f1
还是Clojure?
(->> p f3 f2 f1)
推荐答案
如果您想自己编写而不使用外部库,
If you want to write it yourself without using external libraries,
implicit class Pipe[T](x: T) {
def |> [U](f: T=>U): U = f(x)
}
因此,此implicit class
模式用于扩展方法.这是"pimp my library"模式的简写:
So, this implicit class
pattern is used for extension methods. It's shorthand for the "pimp my library" pattern:
class Pipe[T](x: T) { /*extension methods here*/ }
implicit def anyToPipe[T](x: T) = new Pipe(x)
与任何隐式转换一样,如果方法名称对T
无效,但是隐式范围中有一个函数T => Pipe
,并且该方法在Pipe
上有效,则该函数(或方法-实际上是同一件事)被编译器插入,因此您得到一个Pipe
实例.
As with any implicit conversion, if the method name is not valid for T
, but there is a function T => Pipe
in implicit scope, and the method is valid on Pipe
, the function (or method here - effectively the same thing) is inserted by the compiler so you get a Pipe
instance.
def |> [U](f: T=>U): U = f(x)
这只是一个名为|>
的方法,它具有类型为T=>U
的参数f
,即Function1[T,U]
,其中T
是输入类型,而U
是结果类型.因为我们希望它适用于任何类型,所以我们需要通过添加[U]
在U
上对类型进行参数化的方法. (如果改为使用T=>Any
,则返回的类型将为Any
,用处不大.)返回值只是根据需要将函数应用到原始值.
This is just a method called |>
that has a parameter f
of type T=>U
, i.e. a Function1[T,U]
, where T
is the input type and U
is the result type. Because we want this to work for any type, we need to make the method type-parameterized on U
by adding [U]
. (If we used T=>Any
instead, our return would be of type Any
, which wouldn't be much use.) The return value is just the application of the function to the original value, as required.
这篇关于Scala等于|>在F#或->>中在Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!