user6166509
user6166509

Reputation:

Non-exhaustive pattern in my function head'

transpose' :: [[a]] -> [[a]]
transpose' [[]]    = []
transpose' [[], _] = []
transpose' rows    = (map head' rows) : transpose' (map tail' rows)
  where
    head' (x:_) = x
    tail' (_:xs) = xs

matMult3 :: (Num a) => [[a]] -> [[a]] -> [[a]]
matMult3 a b = [ [ sum $ zipWith (*) ar bc | bc <- (transpose' b) ] | ar <- a ]

Anyone got any ideas as to why this could be throwing up a non-exhaustive? I feel like there is something missing but I'm too new to haskell itself to actually know, I'm self teaching it so that might be why, any advice would be appreciated.

Upvotes: 2

Views: 175

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

I'm not very fluent yet in Haskell, however the following version of transpose' works well for non-ragged matrices:

transpose' :: [[a]] -> [[a]]
transpose' ([x]: xs) = [x: map singleTail' xs] where
    singleTail' [x] = x
transpose' rows = (map head rows) : transpose' (map tail rows) 

E.g.,

>>> transpose' [[1], [2], [3]]
[[1,2,3]]

>>> transpose' [[1,2,3]]
[[1], [2], [3]]

>>> transpose' [[1, 2], [2, 3], [3, 4]]
[[1,2,3],[2,3,4]]

but fails for ragged matrices:

>>> transpose' [[1, 2], [2, 3], [3, 4, 5]]
:3:5-23: Non-exhaustive patterns in function singleTail'

Upvotes: 1

jamshidh
jamshidh

Reputation: 12060

Both head' and tail' don't define what happens if you provide the empty list as a parameter. You need to define the following:

head' [] = ....
tail' [] = ....

Upvotes: 2

Related Questions