Can someone explain the traverse function in Haskell?

后端 未结 5 1923
名媛妹妹
名媛妹妹 2020-12-12 13:14

I am trying and failing to grok the traverse function from Data.Traversable. I am unable to see its point. Since I come from an imperative backgrou

5条回答
  •  情话喂你
    2020-12-12 13:27

    traverse is the loop. Its implementation depends on the data structure to be traversed. That might be a list, tree, Maybe, Seq(uence), or anything that has a generic way of being traversed via something like a for-loop or recursive function. An array would have a for-loop, a list a while-loop, a tree either something recursive or the combination of a stack with a while-loop; but in functional languages you do not need these cumbersome loop commands: you combine the inner part of the loop (in the shape of a function) with the data structure in a more directly manner and less verbose.

    With the Traversable typeclass, you could probably write your algorithms more independent and versatile. But my experience says, that Traversable is usually only used to simply glue algorithms to existing data structures. It is quite nice not to need to write similar functions for different datatypes qualified, too.

提交回复
热议问题