元组有类似的 zipWith 吗? [英] Is there a zipWith analogue for tuples?
问题描述
初步说明:这是对 SeanD 删除的问题 的重制.>
就像列表有 zipWith
一样...
GHCi>zipWith (+) [1,2] [3,4][4,6]
...感觉应该有类似元组的东西,本着...的精神.
tupleZipWith (+) (1,2) (3,4)
...但在base中似乎没有明显类似的东西.我有哪些选择?
一种选择是使用 tuples-homogenous-h98 包,它为具有适当 Applicative
实例的同构元组提供新型包装器:
GHCi>导入 Data.Tuple.HomogenousGHCi>进口控制.ApplicativeGHCi>LiftA2 (+) (Tuple2 (1,2)) (Tuple2 (3,4))元组 2 {untuple2 = (4,6)}GHCi>(>) <$>元组 3 (7,4,7) <*>元组 3 (6,6,6)Tuple3 {untuple3 = (True,False,True)}
如果你有一个除了 tuples-homogenous-h98 之外最喜欢的同构元组/固定大小向量/固定大小列表库,那么它很可能也有合适的 ZipListcode>-like
Applicative
实例.
对于对的问题略有不同的看法,您可能需要考虑 Data.Biapplicative
来自 bifunctors:
GHCi>导入 Data.BiapplicativeGHCi>bimap (+) (+) (1,2) <<*>(3,4)(4,6)
这种方法的一个好处是它可以处理异构对:
GHCi>bimap (+) (+) (1,2.5) <<*>(3,4)(4,6.5)GHCi>bimap (+) (++) (1,"foo") <<*>>(3,酒吧")(4,"foobar")
Preliminary note: this is a respin of a deleted question by SeanD.
Just like there is zipWith
for lists...
GHCi> zipWith (+) [1,2] [3,4]
[4,6]
... it feels like there should be something analogous for tuples, in the spirit of...
tupleZipWith (+) (1,2) (3,4)
... but there doesn't seem to be anything obviously like that in base. Which options do I have?
One option is using the tuples-homogenous-h98 package, which provides newtype wrappers for homogeneous tuples that have appropriate Applicative
instances:
GHCi> import Data.Tuple.Homogenous
GHCi> import Control.Applicative
GHCi> liftA2 (+) (Tuple2 (1,2)) (Tuple2 (3,4))
Tuple2 {untuple2 = (4,6)}
GHCi> (>) <$> Tuple3 (7,4,7) <*> Tuple3 (6,6,6)
Tuple3 {untuple3 = (True,False,True)}
If you have a favourite homogenous tuple/fixed-size vector/fixed-size list library other than tuples-homogenous-h98, odds are that it will also have suitable ZipList
-like Applicative
instances.
For a slightly different take on the matter when it comes to pairs, you might want to consider Data.Biapplicative
from bifunctors:
GHCi> import Data.Biapplicative
GHCi> bimap (+) (+) (1,2) <<*>> (3,4)
(4,6)
One nice thing about this approach is that it can handle heterogeneous pairs:
GHCi> bimap (+) (+) (1,2.5) <<*>> (3,4)
(4,6.5)
GHCi> bimap (+) (++) (1,"foo") <<*>> (3,"bar")
(4,"foobar")
这篇关于元组有类似的 zipWith 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!