Night Train
Night Train

Reputation: 2576

Non-exhaustive patterns with syntactic sugar and pattern matching

I wrote the function fun1 which takes a list and drops every number that is bigger or equal than the previous numbers.

fun1 (l:ls) =
    fun' [l] ls
  where
    fun' a z =
      case z of
        []  -> a
        _   -> fun' (if (head z) < (last a) then a ++ [head z] else a) (tail z)

That works just fine:

> fun1 [4,4,5,9,7,4,3,1,2,0]
=> [4,3,1,0]

In the last line instead of using head z and tail z I want to use z@(x:xs) which is a syntactic sugar I've seen once.

I tried it in fun2, but there I get an Non-exhaustive patterns error. When I use case xs of instead case z of the function runs without throwing an error, but that way it will either skip the last element or I will have to write the operation to apply to the last element again (which I obviously don't want to do).

fun2 (l:ls) =
    fun' [l] ls
  where
    fun' a z@(x:xs) =
      case z of -- "case xs of" would work, but will skip the last element
        []  -> a
        _   -> fun' (if x < (last a) then a ++ [x] else a) xs

This results in an Non-exhaustive patterns error:

> fun2 [4,4,5,9,7,4,3,1,2,0]
*** Exception: main.hs:(4,5)-(7,61): Non-exhaustive patterns in function fun'

Why do I get this error when I try to match the pattern of z?

Upvotes: 1

Views: 64

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

The expression:

fun' a z@(x:xs)> =
    case z of -- "case xs of" would work, but will skip the last element
        []  -> a
        _   -> fun' (if x < (last a) then a ++ [x] else a) xs

makes not much sense, it means that the clause will only "fire" if z is a non-empty list, so the case [] -> … will never fire, since the pattern (x:xs) already restricts the clause to non-empty lists.

You thus can rewrite this to:

fun' a z =
    case z of
        []     -> a
        (x:xs) -> fun' (if x < (last a) then a ++ [x] else a) xs

For the given sample input, this returns:

Prelude> fun2 [4,4,5,9,7,4,3,1,2,0]
[4,3,1,0]

Upvotes: 2

Related Questions