是否可以在scala中创建函数管道?我希望在F#中执行类似以下语法的操作,通过|>实现。操作
indexPairs |> Seq.iter (fun (i,j) -> parents.[j] <- Some nodes.[i])
我知道这可以通过列表理解轻松完成,但想法是做更复杂的事情,比如
indexPairs |> Seq.groupBy fst |> Seq.iter (fun (i, pairs) -> sons.[i] <- pairs |> Seq.map (fun (_,j) -> nodes.[j]) |> Seq.toList)
这有助于在我看来更好地阅读代码。
答案 0 :(得分:3)
您可以使用compose
或andThen
。
val fComposeG = f _ compose g _ // fComposeG(x) equals f(g(x))
val fAndThenG = f _ andThen g _ // fAndThenG(x) equals g(f(x))
答案 1 :(得分:3)
虽然在其他答案中建议使用Scalaz
是完全合理的,但如果要避免添加外部库依赖项,可以为同一目的添加简单值类:
implicit class ChainOps[A](val value: A) extends AnyVal {
def |>[B](f: A => B): B = f(value)
}
def add(other: Int)(x: Int): Int = x + other
def mul(other: Int)(x: Int): Int = x * other
val value = 12
value |> add(9) |> mul(2) // 42
答案 2 :(得分:2)
您可以使用Scalaz管道运算符使用如下语法:
import scalaz.Scalaz._
def f1(a:String):String =a + "1"
def f2(a:String):String =a + "2"
def f3(a:String):String =a + "3"
val text:String = "abc to xyz"
f1(text) |> f3 |> f2
scala> res2: String = abc to xyz132