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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With