Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-exhaustive pattern matching in Haskell

Tags:

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?

like image 379
Crazy Psychild Avatar asked Aug 06 '15 21:08

Crazy Psychild


People also ask

Does Haskell have pattern matching?

(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.)

What does pattern matching mean in Haskell?

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.


1 Answers

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: []
like image 192
Tikhon Jelvis Avatar answered Oct 11 '22 21:10

Tikhon Jelvis