简体   繁体   中英

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?

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 ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM