Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Max number in a list

Tags:

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 ?

like image 330
Harshit Avatar asked Dec 10 '22 10:12

Harshit


2 Answers

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

like image 75
Netwave Avatar answered Dec 27 '22 10:12

Netwave


You have an extra = before the first |.

maximum (x:xs) | (maximum xs) > x = maximum xs
               | otherwise        = x

Note that you compute maximum xs twice which will probably make your code run very slowly.

like image 20
n. 1.8e9-where's-my-share m. Avatar answered Dec 27 '22 10:12

n. 1.8e9-where's-my-share m.