Search code examples
haskellnon-exhaustive-patterns

Haskell: Non-exhaustive patterns in function (simple functions)


I am confused as to why the 1st and 3rd versions of this functions give this error whereas the second definition works fine.

-- head and tail
third :: [a] -> a
third [a] = head (tail (tail[a]))

-- Pattern matching
third2 :: [a] -> a
third2 (_:_:x:_) = x

-- List indexing
third3 :: [a] -> a
third3 [a] = [a]!!2

Thanks in advance


Solution

  • That is odd that the second one does not complain about non-exhaustive patterns, since third2 will not match lists of length zero, one, or two. The third and third3 functions complain because [a] is not a variable, it is a pattern. [a] desugars to (a:[]), so you could have written them as

    third (a:[]) = head (tail (a:[]))
    
    third3 (a:[]) = (a:[]) !! 2
    

    Neither of which will work, as those are single element lists. I suspect what you want is

    third a = head (tail a)
    
    third3 a = a !! 2