*** Exception: Prelude.read: no parsing in Haskell - Parsing, expressions and recursion

This part of the code must be read in two or more numbers (the main function io is omitted), then "+" to give the sum. Rationals are used because later I will do multiplications and 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 error (second) is that the parsing function cannot process

*Main> parse ["1","2","+"] [Number 3]

*** Exception: Prelude.read: no parse

I looked at the Data.Ratio page and on the Internet for this solution, but could not find it and would appreciate some help. Thank,

CSJC

+3
source share
1 answer

First equation

parse ("+":s)(a:b:xs) = parse (s)((solve (Add (Number a) (Number b))):xs)

it should be

parse ("+":s)(a:b:xs) = parse (s)((solve (Add a b)):xs)

since the signature type aand balready have Expressions.

, ,

parse :: [String] -> [Rational] -> Double

parse ("+":s)(a:b:xs) = parse s ((a + b):xs)

( ):

-- Complete solve to handle all cases
solve :: Expression -> Expression
solve expr@(Number _) = expr
solve (Add (Number x) (Number y)) = Number (x + y)
solve (Add x y) = solve (Add (solve x) (solve y))

-- Convert an Expression to Double
toDouble :: Expression -> Double
toDouble (Number x) = fromRational x
toDouble e = toDouble (solve e)

-- parse using a stack of `Expression`s
parse :: [String] -> [Expression] -> Double
parse ("+":s) (a:b:xs) = parse s ((solve (Add a b)):xs)
parse [] (answer:_) = toDouble answer
parse (x:xs) ys = parse xs (Number (toRational (read x :: Double)) : ys)
parse _ _ = 0

-- parse using a stack of `Rational`s
parseR :: [String] -> [Rational] -> Double
parseR ("+":s) (a:b:xs) = parseR s (a+b : xs)
parseR [] (answer:xs) = fromRational answer
parseR (x:xs) y = parseR xs ((toRational (read x::Double)):y)
parseR _ _ = 0

, a Double, , Rational .

parse Rational Expression Number, . , , :

parse [] (answer:xs) = fromRational (toRational (read (show answer)::Float))

answer Expression, Rational, show answer Float, , :

() ,

*Main> parse ["1","2","+"] [Number 3]
*** Exception: Prelude.read: no parse

, , (answer) Number (3 % 1), show (Number (3 % 1)) - "Number (3 % 1)", String, read Float.

+2