Last active
July 15, 2016 21:23
-
-
Save raheelahmad/450dba76672b5ed0de6c0a325e5d2182 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
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