Skip to content

Instantly share code, notes, and snippets.

Last active November 2, 2020 11:12
What would you like to do?
IO monad, naïve implementation
class IO:
def __init__(self, action, arg):
self.action = action
self.arg = arg
def __rshift__(self, func): # this is "bind" (>>)
if self.action == "getLine":
line = input()
return func(line)
elif self.action == "putStrLn":
print(self.arg) # always returns None
return func(None)
elif self.action == "return":
return func(self.arg)
raise RuntimeError("oops")
def unit(v):
return IO("return", v)
def putStrLn(text):
return IO("putStrLn", text)
getLine = IO("getLine", None)
main = (
putStrLn("What's your name?") >> (lambda _:
getLine >> (lambda name:
putStrLn("Hello " + name)
main >> (lambda _: IO.unit(None))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment