Created
June 17, 2014 21:42
-
-
Save davidallsopp/a6b6660a0839a8df730d to your computer and use it in GitHub Desktop.
Trying to explain Haskell-style pure IO to a Python programmer, in the hope that I will understand it better myself (!).
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
# | |
# A crude demo of how IO can be pure yet achieve something. | |
# All functions are pure, including main(). Only __main__ has effects. | |
# | |
class IO: | |
def __init__(self, f): | |
self.f = f | |
def run(self, x): | |
return self.f(x) | |
def bind(self, io): | |
def f(x): io.run(self.run(x)) | |
return IO(f) | |
def printio(s): | |
def f(_): print s | |
return IO(f) | |
def hello(): | |
def f(x): print "Hello " + x | |
return IO(f) | |
def readlineio(prompt): | |
def f(_): return raw_input(prompt) | |
return IO(f) | |
def main(): | |
return printio("Hello").bind(readlineio("What's your name?").bind(hello())) | |
if __name__ == "__main__": | |
#main() # doesn't print anything | |
main().run(None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment