[Haskell-beginners] Guards problem

Magnus Therning magnus at therning.org
Thu Apr 10 07:58:17 UTC 2014


On Thu, Apr 10, 2014 at 9:48 AM, Stijn Muylle <stijnmuylle at gmail.com> wrote:
>
> All,
>
> I ran into a small problem using guards, and I don't really understand what
> I'm doing wrong.
>
> I have this code:
>
> ----------------------------------
> import Data.List.Split
> type Cell = Bool
> data Board = Board [[Cell]] deriving Show
>
> trueList = True : trueList
>
> createBoard :: Int -> Int -> Board
> createBoard x y = Board (chunksOf x (take (x * y) trueList))
>
> getCellAt :: Int -> Int -> Board -> Cell
> getCellAt x y (Board b)
>         | x >= (length b) =  False
>         | y >= (length (b !! 0)) =  False
>         | otherwise     =  (b !! x) !! y
>
> -----------------------------------
>
> When I try to execute this:
>
> getCellAt (-1) 0 $ createBoard 3 3
>
> I get a negative index exception. However, as -1 is smaller than 3 (length
> of the board), I would expect False to be returned.
>
> Am I overlooking something?

I might be looking at it wrong, but won't your code go through

1. -1(x) >= 3(length b) ---> not true, so check next guard
2. 0(y) >= 3(length $ b!! 0) ---> not true, so check next guard
3. True(otherwise) ---> true

/M


More information about the Beginners mailing list