Incomplete patterns [GHC-62161]
Flag: -Wincomplete-patterns
Enabled by: -Wextra
A function definition or case
expression did not cover all cases. This may
result in a run-time crash of the program.
Examples
Sum of a list
The case for the empty list is missing.
Error Message
Main.hs:4:1: warning: [-Wincomplete-patterns] [GHC-62161]
Pattern match(es) are non-exhaustive
In an equation for ‘mySum’:
Patterns of type ‘[Int]’ not matched: []
|
2 | mySum (x : xs) = x + mySum xs
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Main.hs
Before
{-# OPTIONS_GHC -Wincomplete-patterns #-}
mySum :: [Int] -> Int
mySum (x : xs) = x + mySum xs
After
{-# OPTIONS_GHC -Wincomplete-patterns #-}
mySum :: [Int] -> Int
mySum (x : xs) = x + mySum xs
mySum [] = 0
Safe head of a list
The case for the empty list is missing, and for a safe version of head, the return type has to be changed.
Error Message
Main.hs:4:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘safeHead’:
Patterns of type ‘[a]’ not matched: []
|
3 | safeHead (x : xs) = x
| ^^^^^^^^^^^^^^^^^^^^^
Main.hs
Before
{-# OPTIONS_GHC -Wincomplete-patterns #-}
safeHead :: [a] -> a
safeHead (x : xs) = x
After
{-# OPTIONS_GHC -Wincomplete-patterns #-}
safeHead :: [a] -> Maybe a
safeHead (x : xs) = Just x
safeHead [] = Nothing