用列表压缩可遍历的最标准/通用的方法是什么? [英] 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
函数使用状态单子,所以我真正做的就是在高阶函数中捕获代码的命令部分.我不希望这段代码比你的代码执行得更好.但我不认为你能比 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屋!