简体   繁体   中英

instantiate Num class in Haskell

I have Vectorx class and I want to overload "dot product" with operator (*:) in Num class

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 

It seems to me I can NOT add (*:) operator in the instance of Num

In Java, I can add whatever method that I want when I implement interface or extend abstract class.

Any help would be appreciated.

Here is my updated code from suggestion, but I still get "type error"

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

For your case, It is not suitable to subclass Num class for calculating dot product of vector. it just need to constraint the elements of vector is number as:

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

and instance it as:

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

You still able to instance Num to define (+), (*) or etc operations for Vectorx , but that is Irrelevant to above DotPoduct class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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