What's the most standard/generic way to zip a traversable with a list?

*爱你&永不变心* 提交于 2019-11-28 12:27:14
Benjamin Hodgson

What about mapAccumL/mapAccumR?

tzipWith :: Traversable t => (a -> b -> c) -> [a] -> t b -> Maybe (t c)
tzipWith f xs = sequenceA . snd . mapAccumL pair xs
    where pair [] y = ([], Nothing)
          pair (x:xs) y = (xs, Just (f x y))

tzip :: Traversable t => [a] -> t b -> Maybe (t (a, b))
tzip = tzipWith (,)

ghci> tzip [1..] [4,5,6]
Just [(1,4),(2,5),(3,6)]

ghci> tzip [1,2] [4,5,6]
Nothing

On the question of efficiency - under the hood the mapAccum functions use the state monad, so all I've really done is capture the imperative part of your code in a higher-order function. I wouldn't expect this code to perform better than yours. But I don't think you can do much better than the State monad (or ST), given only Traversable t.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!