What is the difference between pure and impure in haskell?

functional-programming, haskell

Solution

Essentially you want to keep as little code as possible in the "impure section". Code written in the IO monad is forever tainted with insecurity. A function with the signature `IO Int` will return an integer in the IO monad, but it could on top of that send nuclear missiles to the moon. We have no way of knowing without studying every line of the code.

For example, let's say you want to write a program that takes a string and appends ", dude" to it.

main = do
  line <- getLine
  putStrLn $ line ++ ", dude"

Some of the parts of the code are required to be in the IO monad, because they have side effects. This includes getLine and putStrLn. However, putting the two strings together does not.

main = do
  line <- getLine
  putStrLn $ addDude line

addDude input = input ++ ", dude"

The signature of addDude shows that it is pure: `String -> String`. No `IO` here. This means we can assume that addDude will behave at least in that way. It will take one string and return one string. It is impossible for it to have side effects. It is impossible for it to blow up the moon.

Problem

What is the difference between pure and impure in haskell? When doing IO in haskell, what does it mean to keep the pure and impure items separate?

Original source