user8585703
user8585703

Reputation:

Haskell - Is Fold polymorphic function?

A function is polymorphic if it works for several different types - and thus, a function is monomorphic if it works only for one type. (wiki.haskell)

As an example, map is polymorphic.

map :: (a -> b) -> [a] -> [b]

However, the function (foo) has a monomorphic type. It will only accept lists of Int:

foo :: (Int -> Int) -> [Int] -> [Int]
foo = map

foldr in Haskell:

foldr f z []     = z 
foldr f z (x:xs) = f x (foldr f z xs) 

Is Fold polymorphic function too?

Upvotes: 0

Views: 279

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233150

You could ask Haskell itself, via GHCi:

Prelude> :t foldr
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

As you can see, it's defined entirely from parametrically polymorphic types (a, b, and t, where t is Foldable).

Upvotes: 2

nicodp
nicodp

Reputation: 2392

Generally speaking, fold is a pattern that allows to traverse the elements of different collections. In the case of foldr, it's applied to lists of any type:

foldr :: (a -> b -> b) -> b -> [a] -> b

So in this sense, it's a polymorphic function.

Upvotes: 1

Related Questions