Created
June 6, 2014 03:35
-
-
Save ahti/d4d44a2ee2958f522f87 to your computer and use it in GitHub Desktop.
Currying in Swift
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 curry<A,B>(fun: (A)->B, arg: A) -> (() -> B) { | |
return { return fun(arg) } | |
} | |
func curry<A,B,C>(fun: (A,B)->C, arg: A) -> ((B) -> C) { | |
return { return fun(arg, $0) } | |
} | |
func square(i: Int) -> Int { return i * i } | |
let sq2 = curry(square, 2) | |
let res = sq2() | |
// => 4 | |
func log(what: String) { | |
println(what) | |
} | |
let lg = curry(log, "foo") | |
lg() | |
// logs "foo" | |
func foo(a: Int, b:Int) -> Int { | |
return a * b | |
} | |
let fo = curry(foo, 2) | |
fo(3) | |
// => 6 | |
func kw(some a:Int, other b:Int) -> Int { | |
return a - b | |
} | |
kw(some: 2, other: 1) | |
let kwa = curry(kw, 10) | |
kwa(50) | |
// => -40 | |
class Adder { | |
var base = 5 | |
func add(a: Int, b: Int) -> Int { | |
return base + a + b | |
} | |
} | |
let adder = Adder() | |
adder.add(2, b: 1) | |
let bla = curry(adder.add, 2) | |
bla(1) // => 8 | |
adder.base = 0 | |
bla(1) // => 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment