第一个方程式,
parse ("+":s)(a:b:xs) = parse (s)((solve (Add (Number a) (Number b))):xs)
应当:
parse ("+":s)(a:b:xs) = parse (s)((solve (Add a b)):xs)
自每一类型签名以来,a
和b
页: 1
<>Or/strong>,根据第二和第三类,将类型改为
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
后者相当细致,因为最终产生了<代码>Double<>/code>,因此没有使用<代码>Rational的实际点。
在您的<代码>parse上,第三种方程式将<代码>Rational转换成Expression
通过Number
的构造者,但以其他方式予以罚款。 然而,第二个方程式含有不同类型的问题:
parse [] (answer:xs) = fromRational (toRational (read (show answer)::Float))
如果answer
要么是Expression
,要么是Rational
,showwer
不能作为Float
加以统一,从而产生错误,如你的编辑所示:
(二) 差错是由于无法处理 par子功能。
*Main> parse ["1","2","+"] [Number 3]
*** Exception: Prelude.read: no parse
在使用第二个方程式时,中值的第一个要素(answer
)为Number (3 % 1)
和show (Number (3 % 1)
为Number (3 % 1)"
,后者不是String
。 可查阅。