如何编写一个 apply 接受多个参数的函数?
这是一个人为的例子:
val sum: List[Int] => Int = l => l.sum
val double: Int => Int = i => i * i
double.compose(sum).apply(List(1,2,3)) //=> 36
val sumAppend: (List[Int], Int) => Int = (l, i) => i :: l sum
double.compose(sumAppend).apply(List(1,2,3), 1) // Attempt to append 1 to list then sum
上面给我一个类型推断错误?
Define compose2
,例如作为扩展方法Function1
:
implicit class ComposeFunction2[A, B, C, D](f1: Function1[C, D]) {
def compose2(f2: Function2[A, B, C]): Function2[A, B, D] =
(a: A, b: B) => f1(f2(a, b))
}
这将比替代方案更快,因为它不分配元组。用法:
scala> val double: Int => Int = i => i * i
double: Int => Int = <function1>
scala> val sumAppend: (List[Int], Int) => Int = (l, i) => i :: l sum
sumAppend: (List[Int], Int) => Int = <function2>
scala> double.compose2(sumAppend).apply(List(1,2,3), 1)
res5: Int = 49
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)