gpt4 book ai didi

scala - 在 Scala 中使用部分应用函数有哪些应用/优势?

转载 作者:行者123 更新时间:2023-12-01 09:13:39 27 4
gpt4 key购买 nike

我们在 Scala 中部分应用了函数-

def sum(a:Int,b:Int,c:Int) = a+b+c

val partial1 = sum(1,_:Int,8)

我想知道使用部分应用函数的优点是什么。还是只是句法上的加法?

最佳答案

一般偏应用函数,《Programming in Scala, 2nd edition》一书提到:

Another way to think about this kind of expression, in which an underscore is used to represent an entire parameter list, is as a way to transform a def into a function value.
For example, if you have a local function, such as sum(a: Int, b: Int, c: Int): Int, you can “wrap” it in a function value whose apply method has the same parameter list and result types.

scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int,b: Int,c: Int)Int
scala> val a = sum _
a: (Int, Int, Int) => Int = <function3>

(此处,a(1, 2, 3) 是以下内容的缩写形式:

scala> a.apply(1, 2, 3)
res12: Int = 6

)

Although you can’t assign a method or nested function to a variable, or pass it as an argument to another function, you can do these things if you wrap the method or nested function in a function value by placing an underscore after its name.

关于scala - 在 Scala 中使用部分应用函数有哪些应用/优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4531108/

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