maxTail = x | otherwise = maxTail where maxTail = " /> maxTail = x | otherwise = maxTail where maxTail = " /> maxTail = x | otherwise = maxTail where maxTail = "/>

Non-exhaustive patterns in function max

557 Views Asked by At

In ghci this code :

let max [] = error "maximum of empty list"  

let max [x] = x  

let max (x:xs)   
    | x > maxTail = x  
    | otherwise = maxTail  
    where maxTail = max xs 

Causes error : *** Exception: <interactive>:26:5-106: Non-exhaustive patterns in function max

What is the non-exhaustible pattern here? The zero elem, single elem and multi elem list are catered for ?

Update : enter image description here

Update 2 :

enter image description here

Update 3 :

Works as expected on Debian (Raspberry Pi) :

enter image description here

2

There are 2 best solutions below

5
sepp2k On BEST ANSWER

By using three separate lets, you're defining three separate, non-exhaustive functions named max, each one shadowing the previous ones. In order to define a multi-case function using let, you use the let keyword ones and then just repeat the function signature at the same indentation for each pattern like this:

let max [] = error "maximum of empty list"
    max [x] = x
    max (x:xs)
      | x > maxTail = x
      | otherwise = maxTail
      where maxTail = max xs

In order for this (or any other piece of code that takes up multiple lines) to work in GHCI, you'll need to start multi-line mode by entering :{ and then exit it afterwards with :} or write it all in one line using ; instead of line breaks (except before | where you'd just write | without a ; or line break in front).

1
Karol S On

GHCi (and in general, let) doesn't allow you to define a function this way. You simply defined 3 functions, overwriting one with another each time.

If you want to keep using GHCi, write something like this:

let max list = case list of
    [] -> error "maximum of empty list"  
    [x] -> x  
    (x:xs) -> 
      if x > maxTail then x else maxTail  
      where maxTail = max xs