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.
The only way to overload a name in Haskell is to use type classes, so you have three choices:
Vector
an instance of Num
and just have multiplication return an error
..+.
or something similar for vector addition.I know that I could make
Vector3
an instance of theNum
typeclass, but that is too restrictive for me; I do not want to define multiplication of a vector by another vector.
That would be the easiest solution, though. You can define multiplication as
(*) = error "vector multiplication not implemented"
Think of the vector operations that you would get for free!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With