Scala函数的部分应用
我试图了解函数部分应用程序在Scala中是如何工作的 为此,我构建了以下简单代码:Scala函数的部分应用,scala,partialfunction,Scala,Partialfunction,我试图了解函数部分应用程序在Scala中是如何工作的 为此,我构建了以下简单代码: object Test extends App { myCustomConcat("General", "Public", "License") foreach print GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print def myCustomConcat(strings: String*): List[Char] = {
object Test extends App {
myCustomConcat("General", "Public", "License") foreach print
GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print
def myCustomConcat(strings: String*): List[Char] = {
val result = for (s <- strings) yield {
s.charAt(0)
}
result.toList
}
def GeneralPublicLicenceAcronym (concatFunction: (String*) => List[Char] ) = {
myCustomConcat("General", "Public", "License")
}
}
将在控制台上打印:GPL
假设现在我想编写一个函数来生成GPL首字母缩写,使用(作为输入参数)我以前的函数来提取每个字符串的第一个字母:
def GeneralPublicLicenceAcronym (concatFunction: (String*) => List[Char] ): List[Char] = {
myCustomConcat("General", "Public", "License")
}
使用部分应用程序运行此新功能:
GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print
我得到这个错误:
错误:(8,46)类型不匹配;找到:Seq[String]required:String generalpublicenceacronym(myCustomConcat())foreach print
为什么??在这种情况下,我可以使用部分应用程序吗?您需要做的就是将
myCustomConcat()
更改为myCustomConcat
,或者实际上只是myCustomConcat
您所做的并不完全是部分应用程序—它只是将方法用作函数值
在某些情况下(需要函数值),编译器会计算出您的意思,但在其他情况下,您通常需要使用\uu
后缀告诉编译器您的意图
“部分应用程序”是指我们向函数提供一些(但不是全部)参数,以创建新函数,例如:
def add(x: Int, y: Int) = x + y //> add: (x: Int, y: Int)Int
val addOne: Int => Int = add(1, _) //> addOne : Int => Int = <function1>
addOne(2) //> res0: Int = 3
另请参见:您只需将
myCustomConcat()
更改为myCustomConcat
,或者实际上只需myCustomConcat
您所做的并不完全是部分应用程序—它只是将方法用作函数值
在某些情况下(需要函数值),编译器会计算出您的意思,但在其他情况下,您通常需要使用\uu
后缀告诉编译器您的意图
“部分应用程序”是指我们向函数提供一些(但不是全部)参数,以创建新函数,例如:
def add(x: Int, y: Int) = x + y //> add: (x: Int, y: Int)Int
val addOne: Int => Int = add(1, _) //> addOne : Int => Int = <function1>
addOne(2) //> res0: Int = 3
另见:
myCustomConcat(_:_*)