Jakub Kopčanský
Jakub Kopčanský

Reputation: 21

Non-exhaustive patterns in function ships

I got this exception, anyone know how to get rid of it? `

*** Exception: hw.hs:(33,1)-(35,53): Non-exhaustive patterns in function ships`

All functions are working fine except for function ships. Its probably something with the list of Tuples, but I can't figure it out. Here is the code:

replace :: Char -> Char
replace c   | c == ' ' = '.'
            | c == '.' = '.'
            | otherwise = 'x';

findChar :: String -> Int -> String
findChar [] y = []
findChar (s:ss) y | y==0 = replace s : findChar ss (y-1)
                | otherwise = ' ' : findChar ss (y-1)

findStr :: Result -> Int -> Int -> Result
findStr [] x y = []
findStr (a:as) x y | x == 0 =  findChar a y : findStr as (x-1) y
                    | otherwise = findChar a (-1) : findStr as (x-1) y

ships :: Result -> [(Int, Int)] -> Result
ships [] [] = []
ships arena ((x,y):xs) = ships (findStr arena x y) xs

Upvotes: 1

Views: 94

Answers (1)

K. A. Buhr
K. A. Buhr

Reputation: 50819

As @chi has mentioned, turning on the -Wall option when compiling can be very useful for catching these problems at compile time instead of run time. You can either include -Wall in the GHC command line, or you can add the pragma:

{-# OPTIONS_GHC -Wall #-}

at the top of your source code to turn it on.

And, as @RobinZigmond has pointed out, your ships function handles the case where both functions are empty lists and the case where the second function is non-empty list, but unless you're positive that ships can never be called as ships nonEmptyList [], you've missed a case!

ships :: Result -> [(Int, Int)] -> Result
ships [] [] = []
ships _  [] = ?????  -- what happens here?
ships arena ((x,y):xs) = ships (findStr arena x y) xs

Upvotes: 2

Related Questions