我是Haskell的新手,所以如果我忽略了一些基本的东西,我会道歉,但我正在创建一个有三个参数的Coord类型:Position,Vector和Scalar。 Coord必须是Num的实例,并且必须具有特定的实现方法。我相信我已经拥有了我所需要的东西,但我假设我错过了一些基本的东西,因为我收到了基于Num实例的错误。
我的代码:
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"
我得到的错误:
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’
任何有关如何使用Num的说明都将非常感激(我假设这是导致错误的原因)
谢谢。
答案 0 :(得分:1)
在查看建议后,我终于找到了一个有效的解决方案。
data Coord = Position (Double, Double) | Vector (Double, Double) | Scalar Double deriving (Show)
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)
(+) (Position (x, y)) (Vector (a, b)) = 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)
(*) (Scalar c) (Vector (a, b)) = Vector (a*c, b*c)
(*) (Position (x1, y1)) (Position (x2, y2)) = Scalar((x1*x2) + (y1*y2))
(*) (Scalar x) (Scalar y) = Scalar (x*y)
(-) (Vector (a, b)) (Position (x, y)) = Position (x-a, y-b)
(-) (Position (x, y)) (Vector (a, b)) = Position (a-x, b-y)
(-) (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"
希望这可以帮助将来犯同样错误的人。
答案 1 :(得分:0)
你的问题:括号。
而不是
negate Position (x, y) = Position (-x, -y)
DO
negate (Position (x, y)) = Position (-x, -y)
前者隐含地暗示negate
是一个带有两个参数的函数 - Position
值构造函数和(x,y)
,而不是类型为Position
的单个参数,因为它将其解析为
((negate Position) (x,y)) = ...
您的其他功能定义也有同样的问题。