Scala元组功能组成

时间:2017-07-06 07:38:04

标签: scala functional-programming tuples

假设我们有Tuple3结果的3个函数:

def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}

我可以这样组成:

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

但我想要这样的事情:

val (x, y, z) = foo(bar(buz("1", "2", "3")))

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:4)

我认为这就是你想要的。

foo _ tupled(bar _ tupled buz("1", "2", "3"))
// res0: (String, String, String) = (foo_bar_buz_1,foo_bar_buz_2,foo_bar_buz_3)

首先,使用eta扩展(_)将方法转换为Function。然后你可以调用它的tupled()方法,它接受一个元组并将它变成所需的参数。

答案 1 :(得分:4)

为了便于输入,假设我们定义了以下类型别名:

type String3 = (String, String, String)

您可以使用andThencompose作为sheunis说,您可以使用Function3[String, String, String, String3]功能将Function1[String3, String3]变为tupled。 然后当与eta扩展结合使用时,你会得到:

val buzBarFoo = (buz _ tupled) andThen (bar _ tupled) andThen (foo _ tupled)

或者这个:

val buzBarFoo = (foo _ tupled) compose (bar _ tupled) compose (buz _ tupled)

两者都具有上述类型的Function1[String3, String3]

然后您可以使用之前使用的功能:

val (x, y, z) = buzBarFoo("1", "2", "3")

答案 2 :(得分:1)

def foo(arg: (String, String, String)): (String, String, String) = {
  (s"foo_${arg._1}", s"foo_${arg._2}", s"foo_${arg._3}")
}

def bar(arg: (String, String, String)): (String, String, String) = {
  (s"bar_${arg._1}", s"bar_${arg._2}", s"bar_${arg._3}")
}

def buz(arg: (String, String, String)): (String, String, String) = {
  (s"buz_${arg._1}", s"buz_${arg._2}", s"buz_${arg._3}")
}

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

val newFunc = foo _ andThen bar andThen buz
newFunc("1", "2", "3")

有两个功能,andThencompose可以执行此操作。它们仅在Function1上定义,您可以通过将元组传递给方法来创建。