Created
December 15, 2014 01:13
-
-
Save JRHeaton/117fe9262aa63970185d to your computer and use it in GitHub Desktop.
functional style repl
This file contains hidden or 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
// see line 65 for program | |
// binary currying | |
func curry<T, U, V>(f: (T, U) -> V) -> T -> U -> V { | |
return { x in { y in f(x, y) }} | |
} | |
// binary uncurry | |
func uncurry<T, U, V>(f: T -> U -> V) -> (T, U) -> V { | |
return { f($0)($1) } | |
} | |
// compose operator (left to right) | |
infix operator ~> { associativity left } | |
// unary composition | |
func ~> <T, U, V>(f: T -> U, g: U -> V) -> T -> V { | |
return { g(f($0)) } | |
} | |
// binary (uncurried) to unary composition | |
func ~> <T, U, V, W>(f: (T, U) -> V, g: V -> W) -> (T, U) -> W { | |
return curry(f) ~> g | |
} | |
// binary (curried) to unary composition | |
func ~> <T, U, V, W>(f: T -> U -> V, g: V -> W) -> (T, U) -> W { | |
return uncurry { f($0) ~> g } | |
} | |
// new function w/ reverse order ("flip") | |
prefix func ~<T, U, V> (f: (T, U) -> V) -> (U, T) -> V { | |
return { f($1, $0) } | |
} | |
infix operator |> { | |
associativity left | |
precedence 0 | |
} | |
func |> <T, U>(x: T, f: T -> U) -> U { | |
return f(x) | |
} | |
func getInput(prompt: String) -> String { | |
print(prompt) | |
fflush(stdout) | |
return NSString(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding: NSUTF8StringEncoding) as String | |
} | |
func printReturn(description: String)(x: String) -> String { | |
print("\(description): \(x)") | |
return x | |
} | |
func loop<T>(f: () -> T) { | |
while true { f() } | |
} | |
let commands = [ | |
"help" : { println("show information about commands") } | |
] | |
let run = { "> " |> | |
getInput ~> // read stdin | |
printReturn("entered cmd") ~> // print the entered cmd | |
{ commands[$0] } ~> // map to the command closure for that command name | |
curry(~map)(println) // using swift's fmap thing here to print since we don't need the value after this (yet) | |
} | |
run |> loop // go repl go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment