Friday, 6 September 2013

foldr vs foldr1 usage in Haskell

foldr vs foldr1 usage in Haskell

If I write:
> let xs = [1,5,19,2,-3,5]
> foldr max 0 xs
19
> foldr1 max xs
19
And if I write (I know, the initial value is incorrect here for a generic
maximum function...):
> let maximum' = foldr max 0
> maximum' xs
19
But if I write:
> let maximum2' = foldr1 max
> maximum2' xs
the response is:
<interactive>:61:11:
Couldn't match expected type `()' with actual type `Integer'
Expected type: [()]
Actual type: [Integer]
In the first argument of maximum2', namely `xs'
In the expression: maximum2' xs
I am new to Haskell. What am I doing wrong? (Can't decipher the error
message...) How to use foldr1 with max? Thanks.
EDIT (AFTER ACCEPTING ANSWER):
Just to show some more examples of the defaulting rules' effect (the
answer explains these, too):
Example 1:
> let max' = max
> :t max
max :: Ord a => a -> a -> a
> :t max'
max' :: () -> () -> ()
Example 2:
> let plus = (+)
> :t (+)
(+) :: Num a => a -> a -> a
> :t plus
> plus :: Integer -> Integer -> Integer

No comments:

Post a Comment