是否有一种标准的方法来总结Num
s的元组?
(1, 2) + (3, 4)
我认为有很多方法可以实现这一目标。举几个例子:编写自己的函数/运算符,使(Num a, Num b) => (a, b)
成为Num
的实例,将一个元组包装在newtype
中等等。
似乎这个问题应该定期出现,但我没有在谷歌或搜索结果中看到任何标准解决方案。我错过了什么吗?
使用vector-space。
Prelude> :m +Data.VectorSpace
Prelude Data.VectorSpace> (1,2) ^+^ (3,4)
(4,6)
Prelude Data.VectorSpace> (1,2,5) ^+^ (3,4,6)
(4,6,11)
Prelude Data.VectorSpace> ((1,2),(9,8)) ^+^ ((3,4),(6,7))
((4,6),(15,15))
Prelude Data.VectorSpace> ((1,2),(9,8)) ^+^ ((3,4),0) -- dimension mismatch
<interactive>:5:1: error:
• No instance for (Num (Integer, Integer))
arising from a use of ‘it’
• In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
如果两个元素都是Monoids,则Pair实现Monoid。
对于Num,您可以使用newtype包装器来选择Monoid
> :m +Data.Monoid
> (Sum 1, Sum 2) <> (Sum 3, Sum 4)
(Sum {getSum = 4},Sum {getSum = 6})
然后你可以通过uncurrying <>
将这两个数字加在一起:
> uncurry (<>) $ (Sum 1, Sum 2) <> (Sum 3, Sum 4)
Sum {getSum = 10}