Skip to content

Instantly share code, notes, and snippets.

@candlerb
Last active November 2, 2020 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save candlerb/d0827043e8852d7c66eebceeeb5dd22a to your computer and use it in GitHub Desktop.
Save candlerb/d0827043e8852d7c66eebceeeb5dd22a to your computer and use it in GitHub Desktop.
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)
else:
raise RuntimeError("oops")
@staticmethod
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