Haskell:评估字符串,包含一个简单的Int算术表达式

时间:2018-12-20 16:35:28

标签: haskell

我正在学习Haskell,遇到一个棘手的问题,该问题正在将包含简单算术表达式(如(+)和(-))的String评估为int。 以一些为例: “ 1 + 2 + 3”-> 6,“”-> 0。 我正在尝试键入代码。但是,我无法完成。以下是我的代码。

evalExpr xs  = foldl f 0 xs where
 f acc x | x == "+" =  (+) acc
         | x == "-" =  (-) acc
         | x == " " = 0
         | otherwise = read x ::Int
* In the expression: read x :: Int
  In an equation for `f':
      f acc x
        | x == "+" = (+) acc
        | x == "-" = (-) acc
        | x == " " = 0
        | otherwise = read x :: Int
  In an equation for `evalExpr':
      evalExpr xs
        = foldl f 0 xs
        where
            f acc x
              | x == "+" = (+) acc
              | x == "-" = (-) acc
              | x == " " = 0
              | otherwise = read x :: Int
* Relevant bindings include
    acc :: a1 (bound at A2.hs:24:8)
    f :: a1 -> [Char] -> a1 -> a1 (bound at A2.hs:24:6)

有人可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您的问题是f的结果类型在不同分支中不同,这是不允许的。在前两行中,它是Int -> Int,即(+) 3的类型(与\x -> 3 + x相同。第三行和第四行的类型仅为Int这些类型不相同。

这是一个简单的解决方案。

data Token = Plus | Minus | Num Int 
lex [] = Nothing
lex ('+':s) = Just (Plus,s)
lex ('-':s) = Just (Minus,s)
lex (num:s) | isDigit num = Just (Num k,rest) where
  numstr a (d:s) | isDigit d = numstr (digitVal d:a) s
  numstr a r = a,r
  digits,rest = numstr [digitVal num] s
  k = foldr 0 (\acc d -> acc*10 + d) digits

parse s = case lex s of
  Nothing -> []
  Just (x,s') -> x:parse s'

eval (Num n:r) = eval (Plus:Num n:r)
eval = eval' 0 where
  eval' acc (Plus:Num n:r) = eval' (acc+n) r
  eval' acc (Minus:Num n:r) = eval' (acc-n) r