什么是用列表压缩可遍历的最标准/通用的方法? [英] What's the most standard/generic way to zip a traversable with a list?
问题描述
Traversable
在某种意义上是容器的类,它的结构有一个路径(可以对应一个列表),其上的元素可以在不解除的情况下被修改结构。因此
Traversable
is in a sense the class of containers whose structure has a "path" (that can correspond to a list), the elements on which can be modified without dissolving the structure. Hence
zipTrav :: Traversable t => t a -> [b] -> Maybe (t (a,b))
zipTrav = evalStateT . traverse zp
where zp a = do
bs <- get
case bs of
[] -> lift Nothing
(b:bs') -> put bs' >> return (a,b)
然而,列表状态遍历看起来有点冒失,最有效的方式来做到这一点。我假设会有一个标准函数完成上述或更常规的任务,但我无法弄清楚它会是什么。
However, that list-state traversal seems a bit hackish and likely not the most efficient way to do it. I'd suppose there would be a standard function that accomplished the above or a more general task, but I can't figure out what it would be.
推荐答案
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
关于这个问题的效率 - 引擎盖下的 mapAccum
函数使用状态monad,所以我所做的只是在高阶函数中捕获代码的命令部分。我不希望这些代码比你的更好。但是我不认为你可以比 State
monad(或 ST
)做得更好,只给出 Traversable t
。
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
.
这篇关于什么是用列表压缩可遍历的最标准/通用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!