Skip to content

Instantly share code, notes, and snippets.

@mgadda
Last active December 17, 2016 04:50
Show Gist options
  • Select an option

  • Save mgadda/542b8d0e9b016f41353b5017a32755fd to your computer and use it in GitHub Desktop.

Select an option

Save mgadda/542b8d0e9b016f41353b5017a32755fd to your computer and use it in GitHub Desktop.
typealias RealWorld = Int
typealias IO<T> = (RealWorld) -> (T, RealWorld)
func putStrLn(_ str: String) -> IO<()> {
return { (world) in
print(str)
return ((), world + 1)
}
}
func readLn() -> IO<String> {
return { world in
return (readLine()!, world + 1)
}
}
infix operator >>
func >><T, U>(_ t: @escaping IO<T>, _ u: @escaping IO<U>) -> IO<U> {
return { world0 in
let (_, world1) = t(world0)
return u(world1)
}
}
infix operator >>=
func >>=<T, U>(io: @escaping IO<T>, fn: @escaping (T) -> IO<U>) -> IO<U> {
return { world0 in
let (t, world1) = io(world0)
let uio: IO<U> = fn(t)
let (u, world2) = uio(world1)
return (u, world2)
}
}
protocol Program {
func main() -> IO<()>
}
func run(program: Program) {
let world: RealWorld = 0
let io = program.main()
let (_, world1) = io(world)
print(world1)
}
// --------------
class MyProgram : Program {
func main() -> IO<()> {
return readLn() >>= { putStrLn("hello, \($0)\n") }
}
}
run(program: MyProgram())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment