I tried several hours from now to implement a custom read function for this data structure:
data Term = Monom(Float, Integer)
| Addition(Term, Term)
| Subtraktion(Term, Term)
| Multiplikation(Term, Term)
| Division(Term, Term)
The idea behind the read function is to parse infix-terms like (+ (+ Monom Monom) Monom)
. For now I tried Monoms which are numbers like 2
which translate to Monom(2,0)
, not expressions like 2x^5
which would translate to Monom(2,5)
.
instance Read Term where
readsPrec _ inp = let [(a,b)] = lex inp in
case a of
-- these are control characters for making the input look nicer
"(" -> readsPrec 0 b
")" -> readsPrec 0 b
" " -> readsPrec 0 b
-- end character -> nothing to do here
"" -> []
-- operators
"+" -> let res = readsPrec 0 b in [Addition(res)]
"-" -> let res = readsPrec 0 b in [Subtraktion(res)]
"*" -> let res = readsPrec 0 b in [Multiplikation(res)]
"/" -> let res = readsPrec 0 b in [Division(res)]
-- monom
c -> let res = readsPrec 0 b in [Monom(read c::Float,0),res]
Sadly this does not work, due to this error (which occurs in the Addition and other Operators):
Couldn't match expected type `(Term, String)'
with actual type `Term'
In the return type of a call of `Addition'
In the expression: Addition (res)
In the expression: [Addition (res)]
Can you please give hints how fix the source? I have no Idea why the expected type is (Term,String)
and how to fix it in a appropriate way.
Thanks for your help!