by themagicalcake · 6y ago · 0 comments
The distinction between functions with side effects and descriptions of what IO will be done at run-time has many practical consequences. For example, if you execute the Haskell code
greet name = do
putStrLn ("Hello, " ++ name)
repeat3 action = do
putStrLn "Doing it thrice."
action
action
action
putStrLn "Done it thrice."
main =
repeat3 (greet "themagicalcake")
you get the following output: Doing it thrice.
Hello, themagicalcake
Hello, themagicalcake
Hello, themagicalcake
Done it thrice.
But if you execute the similar-looking Python script def greet(name):
print ('Hello %s' % name)
def repeat3(action):
print ('Doing it thrice.')
action()
action()
action()
print ('Done it thrice.')
if __name__ == "__main__":
repeat3(greet('themagicalcake'))
you get Hello themagicalcake
Doing it thrice.
Traceback (most recent call last):
File "test.py", line 10, in <module>
repeat3(greet('themagicalcake'))
File "test.py", line 5, in repeat3
action()
TypeError: 'NoneType' object is not callable
instead. The Haskell value `greet "themagicalcake"` has type `IO ()`: it is a value that describes IO to be done at runtime. In contrast, the Python value returned by the call `greet('themagicalcake')` has type `NoneType`, and this value does not describe anything. Calling `greet` itself had the side-effect of printing "Hello themagicalcake".It's not that you couldn't do the same thing in Python, it's that you get more fine and precise control over what happens by default in Haskell.
repeat3(lambda: greet('themagicalcake'))
main = greet "themagicalcake"
in Haskell to get a program that just prints Hello themagicalcake
but the Python program if __name__ == "__main__":
lambda: repeat3(greet('themagicalcake'))
prints nothing.But then the question is what happens if you reuse a RealWorld that you already called a function with. That leads you to types with values that can only be used once, uniqueness types (https://en.wikipedia.org/wiki/Uniqueness_type). Which is the solution for IO that Clean, the other lazy functional language, uses.
For example, console I/O: The input from the console could be transformed (possibly with some state) and sent back out (possibly triggering an associated state update) as a fairly natural pure function call. It would have the type state -> input -> (state', output), and the 'runtime' would be responsible for gluing this all together.