Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Last active July 15, 2016 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raheelahmad/450dba76672b5ed0de6c0a325e5d2182 to your computer and use it in GitHub Desktop.
Save raheelahmad/450dba76672b5ed0de6c0a325e5d2182 to your computer and use it in GitHub Desktop.
Inspired from https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch5.html
// Curries by partially applying 1 out of 2 arguments
func curry<A, B, C>(fn: (A, B) -> C, _ val: A) -> (B -> C) {
return { b in
fn(val, b)
}
}
// "compose" operator
infix operator >> {
associativity left
}
func >> <A, B, C>(f: A -> B, g: B -> C) -> (A -> C) {
return { a in g(f(a)) }
}
// Trace at any point of function composition
func trace<T>(tag: String, _ val: T) -> T {
print("\(tag) -> \(val)")
return val
}
func doubled(number: Int) -> Int { return number * 2 }
func odd(number: Int) -> Bool { return number % 2 == 1 }
let oddAfterDoubling = doubled >> odd
let oddAfterDoubling_withTrace = doubled >> curry(trace, "after add") >> odd
oddAfterDoubling_withTrace(13) // after add -> 26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment