超载 (+)
我试图在 Haskell 中定义 Vector3
数据类型,并允许在其上使用 (+)
运算符。我尝试了以下操作:
data Vector3 = Vector3 Double Double Double
Vector3 x y z + Vector3 x' y' z' = Vector3 (x+x') (y+y') (z+z')
但是 ghci 抱怨 (+)
的出现不明确。我不明白为什么这个事件是模棱两可的;当然,类型检查器可以推断出 x
、x'
、y
等具有类型 Double
,因此是正确的运算符用于它们的是 Prelude.+
?
我知道我可以使 Vector3
成为 Num
类型类的实例,但这对我来说限制太大;我不想定义一个向量与另一个向量的乘法。
I am trying to define a Vector3
data type in Haskell and allow the (+)
operator to be used on it. I tried the following:
data Vector3 = Vector3 Double Double Double
Vector3 x y z + Vector3 x' y' z' = Vector3 (x+x') (y+y') (z+z')
But ghci complains about ambiguous occurrence of (+)
. I do not understand why the occurrence is ambiguous; surely the type checker can infer that x
, x'
, y
etc have type Double
and hence the correct operator to use for them is Prelude.+
?
I know that I could make Vector3
an instance of the Num
typeclass, but that is too restrictive for me; I do not want to define multiplication of a vector by another vector.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Haskell 中重载名称的唯一方法是使用类型类,因此您有三种选择:
Vector
设为Num
的实例,然后让乘法返回一个错误。
.+.
或类似的向量加法名称。The only way to overload a name in Haskell is to use type classes, so you have three choices:
Vector
an instance ofNum
and just have multiplication return anerror
..+.
or something similar for vector addition.不过,这将是最简单的解决方案。您可以将乘法定义为
想象一下您将免费获得的向量运算!
That would be the easiest solution, though. You can define multiplication as
Think of the vector operations that you would get for free!