Last active
December 16, 2016 09:59
-
-
Save josephchang10/64383d7241af6bd706ee94fb7851182b to your computer and use it in GitHub Desktop.
柯里化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func addTo(_ adder: Int) -> (Int) -> Int { | |
return { | |
num in | |
return num + adder | |
} | |
} | |
let addTwo = addTo(2) //addTwo:Int -> Int | |
let result = addTwo(6) //result = 8 | |
let addThreeResult = addTo(3)(9) | |
func greaterThan(_ comparer: Int) -> (Int) -> Bool { | |
return { $0 > comparer } | |
} | |
let greaterThan10 = greaterThan(10) | |
greaterThan10(13) // => true | |
greaterThan10(9) // => false |
Swift 里可以将方法进行柯里化(Currying),这是也就是把接受多个参数的方法进行一些变形,使其更加灵活的方法。函数式编程思想贯穿于 Swift 中,而函数的柯里化正是这门语言函数式特点的重要表现。
柯里化是一种量产相似方法的好方法,可以通过柯里化一个方法模板来避免写出很多重复的代码,也方便了今后维护。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
adder前有一个空格,空格有一个下划线,下划线的作用是忽略外部参数名。