Can someone explain the traverse function in Haskell?

后端 未结 5 1920
名媛妹妹
名媛妹妹 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 turns things inside a Traversable into a Traversable of things "inside" an Applicative, given a function that makes Applicatives out of things.

    Let's use Maybe as Applicative and list as Traversable. First we need the transformation function:

    half x = if even x then Just (x `div` 2) else Nothing
    

    So if a number is even, we get half of it (inside a Just), else we get Nothing. If everything goes "well", it looks like this:

    traverse half [2,4..10]
    --Just [1,2,3,4,5]
    

    But...

    traverse half [1..10]
    -- Nothing
    

    The reason is that the <*> function is used to build the result, and when one of the arguments is Nothing, we get Nothing back.

    Another example:

    rep x = replicate x x
    

    This function generates a list of length x with the content x, e.g. rep 3 = [3,3,3]. What is the result of traverse rep [1..3]?

    We get the partial results of [1], [2,2] and [3,3,3] using rep. Now the semantics of lists as Applicatives is "take all combinations", e.g. (+) <$> [10,20] <*> [3,4] is [13,14,23,24].

    "All combinations" of [1] and [2,2] are two times [1,2]. All combinations of two times [1,2] and [3,3,3] are six times [1,2,3]. So we have:

    traverse rep [1..3]
    --[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
    

提交回复
热议问题