【问题标题】:Pipeline of functions scala函数管道
【发布时间】:2018-01-08 03:37:23
【问题描述】:

是否可以在 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)

在我看来,这有助于提高代码的可读性。

【问题讨论】:

    标签: scala f# functional-programming


    【解决方案1】:

    虽然在其他答案中建议使用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】:

      您可以在 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
      

      【讨论】:

      • 我认为它在 Scala 中意义不大。你可以 。进入有点重载的方法。另外我会像瘟疫一样避免使用 Scalaz,如果 |&gt; 不是一个被广泛接受的运算符,那么就不要使用它。 F# 很棒。
      【解决方案3】:

      您可以使用composeandThen

      val fComposeG = f _ compose g _ // fComposeG(x) equals f(g(x))
      val fAndThenG = f _ andThen g _ // fAndThenG(x) equals g(f(x))
      

      【讨论】:

      • _ 扩展 (ETA) 并不总是需要
      猜你喜欢
      • 2012-03-14
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 2018-11-27
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多