Objectives

  • Gain an understanding of Monads and IO in Haskell

Introduction

Monads in Haskell provide a way of chain togther functions to build a computation. Monads wrap a value of a particular type, which we can think of as being passed through the pipeline of the computation. In fact, the main in Haskell has the following type signature:

main :: IO ()

which is an IO monad which contains the empty tuple (aka it doesn't return anything).

Monads are at the heart of Haskell, and allow us to build familar concepts from procedural programming which may have side effects such as IO safely by wrapping them in the monad.

Learn You A Haskell

Work your way through chapter nine to twelve of Learn You a Haskell. See also the following if you need more explanations:

Monads tend to be the number one sticking point for people leaning functional programming, so make sure to read carefully.

Hello Console!

Now that we finally have access to IO we can finall write some good old fashioned terminal programs! Make sure to read the section on compiling your programs with GHC, as your program for this section should be compiled to an executable (aka it has a main monad), not run through ghci.

First, for a warm up, create a program which accepts an integer n as input on the terminal and then displays the nth fibonacci number. Save it in a file called fib.hs

eg.

    >ghc fib.hs
    >./fib
     Enter n: 2
     1

Next, read about the Eight Queens Puzzle. The puzzle requires finding how to place 8 queens on and 8x8 chess board such that no two queen threaten each other. Your program should accept an integer n, and output a solution for the puzzle on a nxn board with n Queens. The output should be a list of positions (eg. a2, b4, c6, d8, e3, f1, g7, h5). You solution only need to work for integer values up to 8, meaning you are free to use a brute-force solution if you like. Save the code in a file called queen.hs

Feel free to use algorithms found online, but not significant code (recall Ryerson Policy 60). Remember you are being marked on making an effort, not the final output.