Skip to content

Instantly share code, notes, and snippets.

@jamiepinkham
Last active January 6, 2020 20:38
Show Gist options
  • Save jamiepinkham/280a18f0a9e974b9e3ea18613e2c2508 to your computer and use it in GitHub Desktop.
Save jamiepinkham/280a18f0a9e974b9e3ea18613e2c2508 to your computer and use it in GitHub Desktop.
//curries a 2 argument function
func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { x -> (B) -> C in { y -> C in
f(x, y)
}
}
}
func add(x: Int, y: Int) -> Int {
return x + y
}
//curry -> take a function that takes 2 (or more) arguments and convert it to a function that takes one argument and returns a function
let adder = curry(add)
// adder is (Int) -> (Int) -> (Int)
//partially apply the add function (in this case providing the left operand)
let add2 = adder(2)
//add2 is (Int) -> Int
let three = add2(1)
//three == 3, if my elementary math serves me correctly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment