gpt4 book ai didi

scala - 组合具有多个参数的函数

转载 作者:行者123 更新时间:2023-12-02 03:55:10 25 4
gpt4 key购买 nike

如何编写一个 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

上面给了我一个类型推断错误?

最佳答案

定义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

关于scala - 组合具有多个参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com