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

后端 未结 3 1690
孤独总比滥情好
孤独总比滥情好 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:02

    One solution would be to use the State monad with traverse, since it is also Applicative:

    enumerate :: (Integral n, Traversable t) => t a -> t (n, a)
    enumerate t = evalState (traverse go t) 0
        where
            go a = do
                i <- get
                modify (+1)
                return (i, a)
    

提交回复
热议问题