[Haskell-beginners] Regarding defining cases exhaustively

Frerich Raabe raabe at froglogic.com
Mon Oct 10 06:51:52 UTC 2016


On 2016-10-10 07:15, Lai Boon Hui wrote:
> I have this code
> 
> myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
> myMaximumBy _ [] = undefined
> myMaximumBy _ (x:[]) = x
> myMaximumBy f (x:xs) =
>   case f x maxRestOfList of
>     GT -> x
>     _ -> maxRestOfList
>     where maxRestOfList = myMaximumBy f xs
> 
> whereby the case myMaximumBy _ [] will never happen because case myMaximumBy 
> _ (x:[]) = x prevents that from happening.

Somebody could call 'myMaximumBy' with an empty list, so as far as the 
compiler (and fellow programmers) are concerned, this case can certainly 
happen.

> However i will still like to define it to keep -Wall warning from 
> complaining.
> 
> Is using undefined acceptable or is there a better way?

If you're fine with having a partial function (i.e. which is not defined for 
all possible inputs), then 'undefined' is okay. An alternative might be

   myMaximumBy _ [] = error "empty list"

A nicer approach might be to make 'myMaximumBy' a total function though, i.e. 
give a plausible definition even for empty lists. So, for instance, you could 
declare it as

   myMaximumBy :: (a -> a -> Ordering) -> [a] -> Maybe a

such that for empty lists, it yields 'Nothing'.

-- 
Frerich Raabe - raabe at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing


More information about the Beginners mailing list