3
在此代码中,我可以使用一些直接构造函数(如Lit
和Nom
)构造一个列表Algo
,但也可以使用整数。发生这种情况是因为Algo
派生了Num
。字符串的Haskell类型强制
是否有可能为字符串做类似的事情?
type Nr = Double
data Algo
= Nom Nr
| Lit String
| Und
deriving (Show)
instance Num Algo where
(+) (Nom a) (Nom b)=Nom(a+b)
(+) _ _=Und
(*) (Nom a) (Nom b)=Nom(a*b)
(*) _ _=Und
abs (Nom a)=Nom(abs a)
abs _=Und
signum (Nom a)=Nom(signum a)
signum _=Und
fromInteger a=Nom(fromInteger a)
main=do
print ([1,2,3,Und,Nom 5,Lit "x"]::[Algo])
运行正常使用结果:
[Nom 1.0,Nom 2.0,Nom 3.0,Und,Nom 5.0,Lit "x"]
所需的代码:
print (["test",1,2,3,Und,Nom 5,Lit "x"]::[Algo])
会给当然是一个错误... 在什么地方发生转换?在解析/编译?
readPrec都于事无补
你认为''测试''被“转换”到了什么程度? – Shoe
自动与数字一样点亮“测试” –