'Haskell - Max number in a list
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 ?
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
Firstly there is a syntax error, you need to remove the = after maximum (x:xs).
Secondly, the function maximum conflicts with Main.maximum, I suggest you rename it, for example:
maximum' :: [Int] -> Int
maximum' [x] = x
maximum' (x:xs)
| (maximum' xs) > x = maximum' xs
| otherwise = x
Solution 4:[4]
Recursion
Using where Clause
maxrec :: (Ord a) => [a] -> a
maxrec [] = error "maximum of empty list"
maxrec [x] = x
maxrec (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maxrec xs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | n. 1.8e9-where's-my-share m. |
| Solution 3 | vikingsteve |
| Solution 4 | M2Kishore |
