Swift:'Currying'和return函数有什么区别?
Swift: What is the difference between 'Currying' and the function that return a function?
// function 1------- Currying
func increment (incrementBy x: Int)(y: Int) -> Int {
return x + y
}
// function 2------- The function that return a function
func increment(incrementBy x: Int) -> ((Int) ->Int){
func incrementFunc(y: Int){
return x + y
}
}
这两个函数做同样的事情,不是吗?我可以用同样的方式使用它们。像这样:
let incrementFunc = increment(incrementBy: 10)
var number = 10
number = incrementFunc(number)
所以,我很困惑,他们有什么区别?每种方式的优点是什么?
您的第一个示例是 "syntactic sugar" 用于第二个,类似于 [Int]
是 shorthand 用于 Array<Int>
。他们的意思相同,行为方式相同。
但是,我应该指出这种语法糖很快就会消失。 This proposal,由 Swift 编译器工程师编写并被 Swift 开发团队接受,表示 shorthand currying 语法将不再是该语言的一部分。相反,所有柯里化都将按照您编写的第二个示例的方式完成。
第一个函数 2 应该是:
func increment(incrementBy x: Int) -> ((Int) ->Int){
func incrementFunc(y: Int) -> Int {
return x + y
}
return incrementFunc
}
在这种情况下,函数 1 和 2 做完全相同的事情。
第一个有点短。
第二个的意图似乎更清楚。
你也可以使用更短更清晰的函数3:
func increment(incrementBy x: Int) -> ((Int) ->Int){
return { y in return x + y }
}
// function 1------- Currying
func increment (incrementBy x: Int)(y: Int) -> Int {
return x + y
}
// function 2------- The function that return a function
func increment(incrementBy x: Int) -> ((Int) ->Int){
func incrementFunc(y: Int){
return x + y
}
}
这两个函数做同样的事情,不是吗?我可以用同样的方式使用它们。像这样:
let incrementFunc = increment(incrementBy: 10)
var number = 10
number = incrementFunc(number)
所以,我很困惑,他们有什么区别?每种方式的优点是什么?
您的第一个示例是 "syntactic sugar" 用于第二个,类似于 [Int]
是 shorthand 用于 Array<Int>
。他们的意思相同,行为方式相同。
但是,我应该指出这种语法糖很快就会消失。 This proposal,由 Swift 编译器工程师编写并被 Swift 开发团队接受,表示 shorthand currying 语法将不再是该语言的一部分。相反,所有柯里化都将按照您编写的第二个示例的方式完成。
第一个函数 2 应该是:
func increment(incrementBy x: Int) -> ((Int) ->Int){
func incrementFunc(y: Int) -> Int {
return x + y
}
return incrementFunc
}
在这种情况下,函数 1 和 2 做完全相同的事情。 第一个有点短。 第二个的意图似乎更清楚。
你也可以使用更短更清晰的函数3:
func increment(incrementBy x: Int) -> ((Int) ->Int){
return { y in return x + y }
}