我将自己的复数数据类型定义为学习练习,我遇到了重载(/)
运算符的问题。似乎我不能将它包含在Floating
或Fractional
的实例中,编译器说(/)
不是这些类的可见方法。是否有一个(最好是数字)类型类允许我重载此运算符?例如
instance SOMECLASS a => SOMECLASS (Complex a) where
(/) a b@(Complex r i) = fmap (/(r^2 - i^2)) (a * (conjugate b))
以下是感兴趣的人的当前实施实施:
module Complex where
data Complex a = Complex {real :: a, imaginary :: a}
i = Complex 0 1
instance Num a => Show Complex a where
show (Complex r i)
| i < 0 = show r ++ " - i" ++ show (negate i)
| otherwise = show r ++ " + i" ++ show i
instance Functor Complex where
fmap f (Complex r i) = Complex (f r) (f i)
instance Num a => Num (Complex a) where
(+) (Complex ra ia) (Complex rb ib) = Complex (ra + rb) (ia + ib)
(-) (Complex ra ia) (Complex rb ib) = Complex (ra - rb) (ia - ib)
(*) (Complex ra ia) (Complex rb ib) = Complex (ra*rb - ia*ib) (ra*ib + rb*ia)
instance Floating a => Floating (Complex a) where
(/) a b@(Complex r i) = fmap (/(r^2 - i^2)) (a * (conjugate b))
conjugate :: Num a => Complex a -> Complex a
conjugate (Complex r i) = Complex r (negate i)
答案 0 :(得分:3)
在:t (/)
中输入ghci
时,您将获得:
(/) :: Fractional a => a -> a -> a
这意味着它是Fractional
的成员,而不是Floating
的成员。因此,您可以将其重写为:
instance Fractional a => Fractional (Complex a) where
(/) a b@(Complex r i) = fmap (/(r^2 - i^2)) (a * (conjugate b))
由于我们在挑剔,你还必须在Show
个实例中添加括号:
instance Num a => Show (Complex a) where
show (Complex r i)
| i < 0 = show r ++ " - i" ++ show (negate i)
| otherwise = show r ++ " + i" ++ show i