On this code I'm able to construct a list of Algos using some direct constructors like Lit and Nom, but also from integers. This happens because Algo derives Num.
Is it possible to do something similar for strings?
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])
running ok with result:
[Nom 1.0,Nom 2.0,Nom 3.0,Und,Nom 5.0,Lit "x"]
desired code:
print (["test",1,2,3,Und,Nom 5,Lit "x"]::[Algo])
will give an error of course... where does the conversion occurs? at parse/compile?
readPrec didn't help either
For "test" to be automatically "converted" to Algo, you would need to define an instance of IsString and then use the GHC extension OverloadedStrings:
instance IsString Algo where
fromString = Lit
Live demo
So that the following works correctly:
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With