在此处的代码下方Fun with Type Functions
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, TypeFamilies #-}
-- Start basic
class Add a b where
type SumTy a b
add :: a -> b -> SumTy a b
instance Add Integer Double where
type SumTy Integer Double = Double
add x y = fromIntegral x + y
instance Add Double Integer where
type SumTy Double Integer = Double
add x y = x + fromIntegral y
instance (Num a) => Add a a where
type SumTy a a = a
add x y = x + y
-- End basic
这是我试图运行的代码:
main = print $ show (add 1 1)
这是结果:
No instance for (Show (SumTy a0 b0))
arising from a use of `show'
Possible fix: add an instance declaration for (Show (SumTy a0 b0))
In the second argument of `($)', namely `show (add 1 1)'
In the expression: print $ show (add 1 1)
In an equation for `main': main = print $ show (add 1 1)
我已经尝试了一些东西,比如把“数据”放在任何地方:
结果 1
Not a data constructor: `a'
结果 2(删除“instance (Num a)”后)
Multiple declarations of `Double'
Declared at: ...
像添加一些功能:
class Add a b where
type SumTy a b
add :: a -> b -> SumTy a b
s :: SumTy a b -> String
instance Add Integer Double where
type SumTy Integer Double = Double
add x y = fromIntegral x + y
s (SumTy _ x) = show x
main = print $ show (s (add 1 2.0) )
结果:
Not in scope: data constructor `SumTy'
你可能已经注意到我被困住了,所以任何帮助对我来说都是无价的。:)