Haskell type coercion for strings
In this code, I can build a list Algo
using some direct constructors like Lit
and Nom
, but also from integers. This is because it Algo
outputs Num
.
Is it possible to do something like this 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])
works fine with the 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 take place? when parsing / compiling?
readPrec didn't help
source to share
To "test"
be automatically converted to Algo
, you will need to define an instance IsString
and then use the GHC extension OverloadedStrings
:
instance IsString Algo where
fromString = Lit
So, do the following:
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"]
source to share