[Haskell-beginners] Get max element of a list using foldl or foldr
jamb at hinojosa.com
jamb at hinojosa.com
Sat Sep 26 00:10:58 UTC 2015
El 2015-09-25 18:57, Francesco Ariis escribió:
> 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?
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
I´ve got it!
I tried the following successfully:
myMax [] = error "List is empty."
myMax xs = foldl1 (max) xs
I see that my problem was in understanding the way max was applied to a
list.
Thanks for your kind support.
More information about the Beginners
mailing list