This portion of code should read in two or more numbers (main io function omitted), then a “+” to give the sum. Rationals are used because later i will do multiplications and such other operations.
data Expression = Number Rational
| Add (Expression)(Expression)
deriving(Show,Eq)
solve :: Expression -> Expression
solve (Add (Number x) (Number y)) = Number (x + y)
parse :: [String] -> [Expression] -> Double
parse ("+":s)(a:b:xs) = parse s (solve (Add a b):xs)
parse [] (answer:xs) = fromRational (toRational (read (show answer)::Float))
parse (x:xs) (y) = parse (xs) ((Number (toRational (read x::Float))):y)
The (second) error is with the parse function unable to handle
*Main> parse ["1","2","+"] [Number 3]
*** Exception: Prelude.read: no parse
I have looked on the Data.Ratio page and on the web for this solution but haven’t found it and would appreciate some help. Thanks,
CSJC
The first equation,
should be
since per the type signature,
aandbalready areExpressions.Or, in line with the second and third equations, change the type to
and change the first equation to
Two possible ways of fixing the code (there were more problematic parts):
The latter is rather circumspect, since in the end a
Doubleis produced, there’s no real point usingRationals for the stack.In your code for
parse, the third equation leaves out the conversion of aRationalto anExpressionvia theNumberconstructor, but is otherwise fine. The second equation, however, contains a different type of problem:If
answeris either anExpressionor aRational,show answercannot be parsed as aFloat, so that will lead to a runtime error, as exemplified by your edit:At the point where the second equation is used, the first element (
answer) on the stack isNumber (3 % 1), andshow (Number (3 % 1))is"Number (3 % 1)", which is not aStringthatreadcan parse as aFloat.