The purpose of the Traversable typeclass

后端 未结 3 1058
梦毁少年i
梦毁少年i 2021-02-19 09:56

Could someone please explain to me, what is the purpose of the typeclass Traversable?

The typeclass definition is:

class (Functor t, Folda         


        
3条回答
  •  伪装坚强ぢ
    2021-02-19 10:06

    Traversable in Haskell unifies the concept of mapping over a container (getting a similary-shaped container in return) with the concept of "internal iterator" that performs an effect for each element.

    Compared to external iterators, internal iterators are constrained in that we can't use a value obtained for one element to decide what to do with other elements. We can't say "mmmm, if the operation returns 7 for some element, launch the missiles when processing the next one".

    This type of "rigid" computations, that can't change course based on values determined mid-way, is represented in Haskell by the Applicative typeclass. That's the reason Traversable (the containers) and Applicative (the effects) go hand-in-hand. Functor is not enough because it doesn't provide a method to combine effectful actions.

    Allowing any kind of Applicative effect is a boon; it means we can traverse a container performing IO, existing early from failure, collecting log messages, collecting error messages from failed iterations, iterating concurrently... or any combination of those effects.

提交回复
热议问题