tobold.org

correct • elegant • free

△ How to do IO in Haskell △

◅ How do you do?

Input, binding ▻

More output functions

So far we've met putStr and putStrLn. Here is a complete list of all the output functions defined in the Standard Prelude. Note that the type FilePath is a synonym for String.

putStr :: String -> IO ()
Writes its String argument to standard output.
putStrLn :: String -> IO ()
Writes its String argument to standard output, followed by a newline character.
print :: Show a => a -> IO ()
Writes its argument to standard output, followed by a newline character. You can hand a value of any type to print (provided the type is an instance of type class Show).
putChar :: Char -> IO ()
Writes its Char argument to standard output.
writeFile :: FilePath -> String -> IO ()
Writes its String argument to the file named by the FilePath argument. If the file doesn't exist, it will be created; if it does exist, it will be overwritten.
appendFile :: FilePath -> String -> IO ()
Writes its String argument to the end of the file named by the FilePath argument. If the file doesn't exist, it will be created.

Exercises

4. In queens.hs is a definition of queens, which solves the n-queens problem (adapted from Bird and Wadler). For example, queens 9 returns a 352-element list containing all the solutions for a 9x9 board.

Define a function writeQueens that uses writeFile to write the list to a file. For example, main = writeQueens 8 should be a program that creates a file called queens8.out containing all the solutions to the 8-queens problem. Initially, output the list in Haskell format (i.e. use show). What is the file size of queens9.out? Solution: writequeens.hs.

5. Now adapt your solution so that the program writes ASCII board images. For example, a 4x4 board might be output like this:

.X..
...X
X...
..X.

Separate each board image with a blank line. What is the file size of queens9.out now? My first solution, prettyqueens0.hs, takes the obvious route of leaving queens alone and modifying writeQueens. After a little thought, I realised that the type class system allows an alternative solution where writeQueens does not change (but queens itself does, slightly): prettyqueens1.hs.

△ How to do IO in Haskell △

◅ How do you do?

Input, binding ▻