Languages such as Haskell require that all functions behave like mathematical functions. For instance:
- Given the same inputs they must always produce the same outputs.
- They should not produce 'side-effects'
These requirements would prevent the language from having input or output and all languages need these or there would not be any point to them.
Haskell allows input/output like this:
main = do putStrLn "type something" userinput <- getLine putStrLn $ "you typed:" ++ userinput |
This uses a way to isolate these 'non-pure' functions using monads.
The functions such as putStrLn and getLine do not return anything that would make them 'non-pure', instead they return IO, this is always the same for given inputs and therefore does not contravene the requirements. However IO contains a function to get the input say which can be called form outside the 'pure' code.
The 'do' construct in the program above links these functions together. This creates a separate 'program' within the Haskell code. | |
This could be redrawn as an endo-function: |