I am learning Haskell and wanted to write a simple program which just repeats each letter in a string twice.
I came up with this:
repl :: String -> String
repl " " = " "
repl (x:xs) = x:x:repl xs
When compiling, I didnt get any warning but a run-time error occurred when I did repl "abcd"
:
"abcd*** Exception: repl.hs:(2,1)-(3,23): Non-exhaustive patterns in function repl
Why did the compiler never report this and why is it ignored in Haskell when there are many languages like OCaml which clearly report this at compile time?
(Pattern matching in Haskell is different from that found in logic programming languages such as Prolog; in particular, it can be viewed as "one-way" matching, whereas Prolog allows "two-way" matching (via unification), along with implicit backtracking in its evaluation mechanism.)
Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.
The pattern match warning is turned off by default. You can turn it on with the -fwarn-incomplete-patterns
or as part of a larger bundle of warnings with -W
and -Wall
.
You can do this from ghci
:
Prelude> :set -W
You can also pass the flag to ghc
when you compile or include it as a pragma on top of your module:
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
For your specific program, it should give the following warning:
/home/tjelvis/Documents/so/incomplete-patterns.hs:2:1: Warning:
Pattern match(es) are non-exhaustive
In an equation for ‘repl’: Patterns not matched: []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With