I am new to Haskell so I apologize if I am overlooking something basic, but I am creating a Coord type that has three parameters: Position, Vector, and Scalar. Coord must be an instance of Num and must have specific implemented methods in it. I believe I have what I need already, but I'm assuming I'm missing something basic because I get an error based on the Num instance.
My code:
data Position x y = Position (x, y)
data Vector x y = Vector (x, y)
data Scalar n = Scalar n
data Coord x y n = Coord (Position x y, Vector x y, Scalar n)
instance Num Coord where
negate (Position (x, y)) = Position (-x, -y)
negate (Vector (x, y)) = Vector (-x, -y)
(+) (Vector (a, b) Position (x, y)) = Position (x+a, y+b)
(+) (Vector (a, b) Vector (c, d)) = Vector (c+a, d+b)
(+) (Scalar x Scalar y) = Scalar (x+y)
(*) (Vector (a, b) Scalar c) = Vector (a*c, b*c)
(*) (Position (x1, y1) Position (x2, y2)) = (x1*x2) + (y1*y2)
(*) (Scalar x Scalar y) = Scalar (x*y)
(-) (Vector (a, b) Position (x, y)) = Position (x-a, y-b)
(-) (Position (x1, y1) Position (x2, y2)) = Vector (x2-x1, y2-y1)
(-) (Scalar x Scalar y) = Scalar (x-y)
abs (Position (x, y)) = Scalar sqrt((x*x)+(y*y))
abs (Vector (x, y)) = Scalar sqrt((x*x)+(y*y))
signum _ = error "undefined"
fromInteger _ = error "undefined"
The error I get:
Expecting three more arguments to ‘Coord’
The first argument of ‘Num’ should have kind ‘*’,
but ‘Coord’ has kind ‘* -> * -> * -> *’
In the instance declaration for ‘Num Coord’
Any clarification on how to use Num would be much appreciated (I'm assuming that is what's responsible for the error)
Thank you.
instance Num Coord where
line: you probably want something likeinstance (Num x, Num y, Num n) => Num (Coord x y n) where
. This is becauseNum
expects a fully "filled-out" type as its argument: you can write an instanceNum Int
orNum (Maybe Int)
, but notNum Maybe
orNum []
. – LynnCoord
as a type, not a function. – LynnCoord
has aPosition
, aVector
and aScalar
inside of it (which would add up to a five dimensional value)? – David Young