繁体   English   中英

实例化Haskell中的Num类

[英]instantiate Num class in Haskell

我有Vectorx类,并且想在Num类中使用运算符(*:)重载"dot product"

data Vectorx a = Vectorx a a a 

instance (Num a)=>Num(Vectorx a) where
    (+) ...
    (-) ...
    etc ...
    (*:) (Vectorx x0 y0 z0) (Vectorx x1 y1 z1) = x0*x1 + y0*y1 + z0*z1 

在我看来,我不能在Num实例中添加(*:)运算符

在Java中,我可以添加实现接口或扩展抽象类时想要的任何方法。

任何帮助,将不胜感激。

这是我从建议中得到的更新代码,但仍然出现“类型错误”

data Vectorx a = Vectorx a a a

class Num a => (VectorOp a) where
    (*:)::Num b=> a -> a -> b

instance (Num a) => Num(Vectorx a) where
    (+) _ _ = undefined

instance VectorOp (Vectorx a) where
    (*:) (Vectorx x0 y0 z0) (Vectorx x1 y1 z1) = x0*x1 + y0*y1 + z0*z1

对于您的情况,不适合将Num类作为子类来计算向量的dot product 它只需要将vector的元素约束为number即可:

class DotProduct v where
    (*:)::Num a=>v a ->v a -> a

并将其实例为:

data Vectorx a = Vectorx a a a

instance DotProduct Vectorx where
    (*:) (Vectorx x0 y0 z0) (Vectorx x1 y1 z1) = x0*x1 + y0*y1 + z0*z1

您仍然可以实例化Num来为Vectorx定义(+), (*)或其他操作,但这与上面的DotPoduct类无关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM