Last active
November 2, 2020 11:12
-
-
Save candlerb/d0827043e8852d7c66eebceeeb5dd22a to your computer and use it in GitHub Desktop.
IO monad, naïve implementation
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
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