[Haskell-cafe] basic haskell question

Glynn Clements glynn at gclements.plus.com
Sun May 22 05:02:15 EDT 2005


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 <glynn at gclements.plus.com>


More information about the Haskell-Cafe mailing list