[Haskell-beginners] Get max element of a list using foldl or foldr

Francesco Ariis fa-ml at ariis.it
Fri Sep 25 23:57:32 UTC 2015


On Fri, Sep 25, 2015 at 06:18:08PM -0500, jamb at hinojosa.com wrote:
> Hello,
> 
> I am a complete Haskell beginner and I am doing some exercises of my book
> but I am stuck with the following:
> 
> Define
> myMax :: Ord a => [a] -> a
> which returns the maximum element of a list.
> 
> I must use foldl1 or foldr1 and I am given the hint to use max which gets
> the maximum of 2 elements.
> 
> I will very much appreciate if you help me solve it.

Let's say you have

    foldl1 f [1,7,2,5]

where f is a binary operator (a function that 'takes two parameters').
`foldl1` will apply 1 and 7 to f, obtaining X, so we have:

    X and [2,5]

then it will apply X and 2 to f, obtaining Y, so we're left with

    Y and 5

and finally `f Y 5`, leading to your final result Z.

Now, if `f a b = a + b`, we would have

       [1,7,2,5]  -- 1+7
    8  [2,5]      -- 8+2
    10 [5]        -- 10+5
    15 <-- final result

But you aren't interested in the sum of the list, but its maximum.
Which operation could you use instead of (+) to achieve your goal?


More information about the Beginners mailing list