Haskell – Max number in a list

haskell

I want to find the maximum integral value in a list of integers. The following is my code –

maximum :: [Int] -> Int
maximum [x] = x
maximum (x:xs) =
 | (maximum xs) > x = maximum xs
 | otherwise = x

I do NOT want to use the in-built function max. So, I have NOT used :
maximum (x:xs) = max x (maximum xs)

Why is the code not executing ?

Best Answer

You should remove the = before the wards block. Now, for making your function properly:

You can fold the list:

maximum' :: Ord a => [a] -> a
maximum' = foldr1 (\x y ->if x >= y then x else y)

For the recursive version (no double checking):

maximum'' :: Ord a => [a] -> a
maximum'' [x]       = x
maximum'' (x:x':xs) = maximum' ((if x >= x' then x else x'):xs)

If you want wards:

maximum'' :: Ord a => [a] -> a
maximum'' [x]       = x
maximum'' (x:x':xs) | x >= x'   = maximum' (x:xs)
maximum'' (x:x':xs) | otherwise = maximum' (x':xs)

Here you have a live example