[Haskell-beginners] Problems defining a type with a multiplication function

Joe Fredette jfredett at gmail.com
Wed Sep 9 17:05:04 EDT 2009


You need to write an instance of the Num class, eg


     instance Num Quaternion where
           (Q a b c d) + (Q e f g h) = ...
           (Q a b c d) * (Q e f g h) = ...
           etc

This allows Haskell to overload things like numbers. You seem to be  
headed in the right direction w/ your type
signature, except (*) has type

     Num a => a -> a -> a

Which means "For any type `a` that is an instance of the type class  
`Num`, this is a closed binary function on that type"

HTH

/Joe


On Sep 9, 2009, at 4:51 PM, Amy de Buitléir wrote:

> I'm trying to define a Quaternion, which is sort of a four-element  
> vector with special rules for multiplication.
>
> ----- Quaternion.hs -----
> data Quaternion = Quaternion Double Double Double Double
>                   deriving (Show)
>
> (*) :: (Quaternion a) => a -> a -> a
> (*) (Quaternion w1 x1 y1 z1) (Quaternion w2 x2 y2 z2) = Quaternion w  
> x y z
>         where w = w1*w2 - x1*x2 - y1*y2 - z1*z2
>               x = x1*w2 + w1*x2 + y1*z2 - z1*y2
>               y = w1*y2 - x1*z2 + y1*w2 + z1*x2
>               z = w1*z2 + x1*y2 - y1*x2 + z1*w2
>
> ----- end code -----
>
> When I try to load this into ghci, I get:
>
> Quaternion.hs:6:13:
>     Ambiguous occurrence `*'
>     It could refer to either `Main.*', defined at Quaternion.hs:5:0
>                           or `Prelude.*', imported from Prelude
>
> ... and lots more messages like that. I understand roughly what the  
> message means, but I don't know how to tell it that when I use "*"  
> within the definition, I just want ordinary multiplication. Thanks  
> in advance for any help!
>
> Amy
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners



More information about the Beginners mailing list