haskellsyntaxfunctional-programmingpattern-matchingnon-exhaustive-patterns

Haskell take first and seventh


I need to write a function in Haskell that given a list of at least 7 elements returns a tuple containing the first and seventh element.

e.g.

Prelude> take1and7 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
(1, 7)

I've tried this

take1and7 :: [a] -> (a, a)
take1and7 [a, b, c, d, e, f, g, xs] = (a, g)

But it says that it has "non-exhaustive patterns" which I don't understand


Solution

  • ... [a, b, c, d, e, f, g, xs] = ...
    

    is a pattern which matches an 8 elements long list. xs names the 8th element, not the rest of the list.

    In case you call this function with a list of 6, 7, 9, etc. elements, the pattern won't match.

    ... (a: b: c: d: e: f: g: xs) = ...
    

    is a pattern which matches a list of 7 elements or longer. xs names the rest of the list after its first 7 elements. With it, the function still won't be able to handle any list shorter than 7 elements.

    The "non-exhaustive" phrasing means our function doesn't handle all possible cases.