haskellghciwinghci

Non-exhaustive patterns in function max


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


Solution

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