【发布时间】:2014-02-05 20:43:42
【问题描述】:
假设我有两种方法
scala> def a(a: Int, b: Int, c: Int) : Int = …
a: (a: Int, b: Int, c: Int)Int
scala> def b(i: Int) : Int = …
b: (i: Int)Int
如何定义一个方法c,即两者的组合?
不幸的是,以下代码无法编译:
def c = b(a)
【问题讨论】:
标签: scala
假设我有两种方法
scala> def a(a: Int, b: Int, c: Int) : Int = …
a: (a: Int, b: Int, c: Int)Int
scala> def b(i: Int) : Int = …
b: (i: Int)Int
如何定义一个方法c,即两者的组合?
不幸的是,以下代码无法编译:
def c = b(a)
【问题讨论】:
标签: scala
您可以将方法a 转换为函数,然后像这样使用方法andThen:
def a(a: Int, b: Int, c: Int) : Int = a + b + c
def b(i: Int) : Int = i * 2
val c = (a _).tupled andThen b
c(1, 1, 1)
// 6
请注意,我必须将函数 (Int, Int, Int) => Int 转换为元组版本 - ((Int, Int, Int)) => Int - 此处使用 andThen。所以结果函数c 接受Tuple3 作为参数。
您可以使用Function.untupled 将c 转换为非元组版本((Int, Int, Int) => Int):
val untupledC = Function.untupled(c)
untupledC(1, 1, 1)
// 6
没有untupled 函数arity > 5的方法。
您也可以使用 shapeless toProduct/fromProduct 方法来处理任何这样的数组:
import shapeless.ops.function._
import shapeless.ops.function._
val c = (a _).toProduct.andThen(b).fromProduct
【讨论】:
Scalaz 定义了 Functor 实例用于更高数量的函数,因此您可以编写
(a _).map(b)
【讨论】: