Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading (+)

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.

like image 444
xuanji Avatar asked Oct 04 '11 10:10

xuanji


2 Answers

The only way to overload a name in Haskell is to use type classes, so you have three choices:

  • Make Vector an instance of Num and just have multiplication return an error.
  • Use something like the numeric prelude, which defines more fine-grained numeric classes.
  • Pick some other name like .+. or something similar for vector addition.
like image 75
hammar Avatar answered Sep 20 '22 06:09

hammar


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.

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!

like image 27
Fred Foo Avatar answered Sep 21 '22 06:09

Fred Foo