Why doesn't a class like Functor include a bend method?

Why does type Functor class only have fmap member? It is often useful for me to bend data types. Say hierarchical like a tree.

Note that a map is a special case of fold , i.e. the latter is more fundamental. I guess I can do it, but maybe there is a reason?

+4
source share
2 answers

Because Functor is a very general view of an object; Not all Functor folds support. For example, there is instance 1

 instance Functor (a ->) where -- > fmap :: (b -> c) -> (a -> b) -> (a -> c) fmap fg = g . f 

But, although (a ->) is a Functor for all a , for infinite a there is no reasonable definition of fold . (By the way, the summary is generally catamorphism , which means it has different types for each funter. A class of type Foldable defines it for types similar to a sequence.).

Let's look at the definition of foldr for Integer -> Integer ; What would be the most external application? What will be the value

 foldr (\ _ n -> 1 + n) 0 (\ n -> n + 1) 

be? There is no reasonable definition of fold without a much larger argument type structure.

1 (a ->) for some reason is not legal Haskell. But I will still use it as a more readable version (->) a , since I think it’s easier for a beginner to understand.

+12
source

The abstraction you are looking for is Foldable : This is a type class that provides various forms of fold .

There is also Traversable for things where you can "add on change", which is comparable to the mapAccumL function for lists.

It’s actually not that fmap is a special case of fold , as pointed out by @DietrichEpp, see here for possible non-Functor instances for Foldable .

map , however, is a special case of mapAccumL (not surprising given the name), and therefore the definition of Traversable requires that the item also be Functor and a Foldable .

+6
source

All Articles