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

John Dorsey haskell at colquitt.org
Wed Sep 9 17:02:47 EDT 2009


Amy,

> 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

You're redefining (*) in Main, which creates the ambiguity, which is the
problem.  One alternative is, instead of creating a new ambiguous (*), is
use the existing one, and make it apply to your type.

The existing (*) belongs to the typeclass Num.  You can make your type an
instance of Num, with your definition of (*):

instance Num (Quaternion a) where
  q1 * q2 = ...
  q1 + q2 = undefined -- or, better, a valid definition
  q1 - q2 = undefined
  ...

You'll find that this cascades into requiring you to define a handful of
other class functions (+, -, negate, abs, signum, fromInteger) and you'll
need Eq and Show instances.  You can derive the latter, and you can give
trivial (undefined or error) definitions for, say, negate if you won't be
using it.

Hope this helps.

John



More information about the Beginners mailing list