Lecture 23-1
So far, we have studied pure functional programming. Pure functions:
- Have no side effects.
- Always return a value.
- Are deterministic.
All computation can be done in pure functional programming.
IO
Sometimes programs need to do non-pure things:
- Print something to the screen.
- Read or write a file.
- …
IO v.s. Pure Functional
graph LR
IO --> p[Pure Functional]
p --> IO
- Impure IO code talks to the outside world.
- Pure functional code does the interesting computation.
- IO code can call pure functions; pure functions cannot call IO.
We can call the “functions” that complete IO: IO actions. This is because they are not functions.
getLine
getLine
read a line of input from the console.
> getLine
hello there
"hello there"
> :t getLine
getLine :: IO String
The IO
Type
This type marks a value as being impure.
If a function returns an IO
type then it is impure:
- It may have side effects.
- It may return different values for the same inputs.
The IO
type should be thought of as a box:
- The box hold a value from an impure computation.
- we can use
<-
to get an impure value from theIO
type.
> x <- getLine
Hello
> x
"Hello"
Values must be unboxed before you use them in a pure function.
getChar
This function is similar to getLine
but returns a single Char
instead of a string.
putStrLn
This IO action prints a string onto the console.
> putStrLn "Hello"
Hello
There are no quotation marks as we are seeing this being written to the StdOut
and not via read
.
> :t putStrLn
putStrLn :: String -> IO ()
The unit type has the IO
type indicating that it has a side effect.
The Unit Type
The unit type is a type represented by ()
. It only has one value which is itself.
This is used to indicate that nothing interesting is returned. An example of this is with putStrLn
where is doesn’t return a value but does have the side effect of printing to the StdOut
.
Exercise
- It will ask for two lines. It will then print out the two lines with a space between them back to the
StdOut
. - It will read in a line with the expectation that there will be a number on it. It will then convert the line into an
Int
and print out the number+ 1
. - Error due to mismatched types.
putStrLn
expects aString
but anIO
type was given.