-1

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!

4

1 回答 1

1

readsPrecforTerm应该返回[(Term, String)]。所以你返回的地方[Addition (res)],你需要[(Term, String)]但实际上有一个[Term]. 请注意,参数也是错误的:resis a [(Term, String)],但Addition(res)您需要它是(Term, Term),因此您需要稍后修复它。

于 2012-10-23T09:07:21.940 回答