haskell - Typeclasses for overloading division -
i'm defining own complex number data type learning exercise, , i've run trouble overloading (/)
operator. seems can't include in instance of floating
or fractional
, compiler saying (/)
isn't visible method of classes. there (preferably numeric) typeclass allow me overload operator? eg.
instance someclass => someclass (complex a) (/) b@(complex r i) = fmap (/(r^2 - i^2)) (a * (conjugate b))
here's current implementation implementation interested:
module complex data complex = complex {real :: a, imaginary :: a} = complex 0 1 instance num => show complex show (complex r i) | < 0 = show r ++ " - i" ++ show (negate i) | otherwise = show r ++ " + i" ++ show instance functor complex fmap f (complex r i) = complex (f r) (f i) instance num => num (complex a) (+) (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 => floating (complex a) (/) b@(complex r i) = fmap (/(r^2 - i^2)) (a * (conjugate b)) conjugate :: num => complex -> complex conjugate (complex r i) = complex r (negate i)
when type :t (/)
in ghci
, obtain:
(/) :: fractional => -> ->
so means member of fractional
, not floating
. can rewrite to:
instance fractional => fractional (complex a) (/) b@(complex r i) = fmap (/(r^2 - i^2)) (a * (conjugate b))
and since nitpicking, have add brackets show
instance:
instance num => show (complex a) show (complex r i) | < 0 = show r ++ " - i" ++ show (negate i) | otherwise = show r ++ " + i" ++ show i
Comments
Post a Comment