
hi, Anybody could please tell me that in the following two expressions what value does the [] take? foldl (/) 3 [] foldr (/) 3 [] when both of them are evaluated I got 3.0,but I thought I could get nothing out of there,cause its an empty list,does Haskell assume any default value for a empty list? -- ------------------------------------------------------------------------------------------------------- If you didn't succeed at the first attempt, you are just about average.

wenduan wrote:
Anybody could please tell me that in the following two expressions what value does the [] take?
foldl (/) 3 [] foldr (/) 3 []
when both of them are evaluated I got 3.0,but I thought I could get nothing out of there,cause its an empty list,does Haskell assume any default value for a empty list?
Those functions are defined as:
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
Note the base cases:
foldl f z [] = z
and:
foldr f z [] = z
If you want functions which fail on an empty list, use:
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
--
Glynn Clements

At 12:50 AM +0800 2005/5/23, wenduan wrote:
hi, Anybody could please tell me that in the following two expressions what value does the [] take?
foldl (/) 3 [] foldr (/) 3 []
when both of them are evaluated I got 3.0,but I thought I could get nothing out of there,cause its an empty list,does Haskell assume any default value for a empty list?
A quick check of the equations that define foldl and foldr (see Prelude.hs) shows that when either of them has an empty list for its third argument, it returns its second argument. Regards, --Ham -- ------------------------------------------------------------------ Hamilton Richards, PhD Department of Computer Sciences Senior Lecturer The University of Texas at Austin 512-471-9525 1 University Station C0500 Taylor Hall 5.138 Austin, Texas 78712-0233 ham@cs.utexas.edu hrichrds@swbell.net http://www.cs.utexas.edu/users/ham/richards ------------------------------------------------------------------
participants (3)
-
Glynn Clements
-
Hamilton Richards
-
wenduan