在此代码上,我可以Algo
使用一些直接构造函数(如Lit
和)构造s列表Nom
,但也可以从整数构造。这是因为Algo
派生而发生的Num
。
可以对字符串做类似的事情吗?
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也没有帮助
对于"test"
被自动“转换”来Algo
,你就需要定义的一个实例IsString
,然后使用GHC扩展OverloadedStrings
:
instance IsString Algo where
fromString = Lit
因此,以下内容可以正常工作:
print ["test", 1, 2, 3, Und, Nom 5, Lit "x"]
-- [Lit "test",Nom 1.0,Nom 2.0,Nom 3.0,Und,Nom 5.0,Lit "x"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句