Lecture 24-2
Useful IO Functions
This lecture covers many useful functions included with Haskell. I won’t be writing out examples but I will be writing down names and descriptions to search through.
For more detailed examples view the slides for this lecture.
print
This prints out any show
-able type.
putStr
This prints a string without adding a new line.
With this you have to manually end the line with:
putStr '\n'
readLn
This function gets a line of input and then calls read
. This saves you calling read when getting a line with getLine
.
To give an explicit type use the syntax:
x <- readLn :: IO Int
This is due to the fact that when readLn
is reading the line it is still in the IO
‘box’.
forever
This repeat an IO action forever. It is in the Control.Monad
package. This is a higher order IO action as it takes another IO action as an input.
It can be used to make interactive code that runs a function forever.
sequence
This IO action will run a list of IO actions and will return a list containing the return values of the IO actions.
The IO actions must have the same type otherwise they can’t be put in the same list.
sequence
works well with map
:
sequence (map print [1..10])
This saves you typing out all the IO actions to sequence
on.
sequence_
This IO action is the same as sequence
but it will return the type IO ()
. You would want to use this when the IO actions you are running return IO ()
themselves.
mapM
You can use this map on monads. This is similar to running sequence
in conjunction with map
. This is the same as the code from before:
mapM print [1..10]
mapM_
This is similar to sequence_
.
when
This executes an IO action if a condition is true.
when True (putStrLn "hi")
This is similar to if
in pure functional code.
unless
This is the opposite of when. It will execute if the condition is false.
Exercises
-
timesTwo = do n <- readLn :: IO Int print (n * 2)
-
import Control.Monad ltFiveOnce = do x <- getLine when (length x < 5) (putStrLn "yes") when (length x >= 5) (putStrLn "no") ltFive = forever ltFiveOnce
-
addThree = do x <- sequence [readLn,readLn,readLn] print (sum x)