How would I use lens in Haskell to duplicate Python's enumerate?

后端 未结 3 1722
孤独总比滥情好
孤独总比滥情好 2021-01-13 19:37

Python\'s enumerate on lists can be written as zip [0..]. I looked at Control.Lens.Traversal and Control.Lens.Indexed, but I couldn\'t figure out how to use len

3条回答
  •  轮回少年
    2021-01-13 20:27

    You're ignoring the Applicative context on itraverse. You need something for it to be working with. But the something can be boring, like Identity.

    imap f = runIdentity . itraverse (\i a -> return (f i a))
    

    And then you get what you're looking for:

    > imap (,) [1,2,3]
    [(0,1),(1,2),(2,3)]
    

提交回复
热议问题