Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Created June 17, 2014 21:42
Show Gist options
  • Save davidallsopp/a6b6660a0839a8df730d to your computer and use it in GitHub Desktop.
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 (!).
#
# 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