在Haskell调试中评估算术字符串

时间:2016-10-26 14:40:36

标签: string debugging haskell arithmetic-expressions

我试图接受一个字符串,评估并输出答案。例如:如果输入是字符串" 2 *(3 + 10)"然后输出应该是int 26

目前,它还没有工作。我有空白问题。如果代码输入中有空格,我会得到***Exception: Char.digitToInt: not a digit ' '。如果输入中没有空格,我会得到*** Exception: Prelude.!!: index too large

import Data.Char

parseExpr :: String -> Int
parseExpr str = start(trim (str))

trim :: [Char] -> [Char]
trim xs = [ x | x <- xs, not (isSpace x)]


start :: [Char] -> Int
start xs = expression xs 0


expression :: [Char] -> Int -> Int 
expression xs i  
    |(xs !! (((basic xs i (-1))!! 1)+1)) == '+' = (multiply xs ((basic xs i (-1))!! 1)) + (multiply xs ((basic xs (i+2) (-1))!! 0))
    |(xs !! (((basic xs i (-1))!! 1)+1)) == '-' = (multiply xs ((basic xs i (-1))!! 1)) - (multiply xs ((basic xs (i+2) (-1))!! 0))
    |otherwise = multiply xs i


multiply :: [Char] -> Int -> Int 
multiply xs i  
     | (xs !! (((basic xs i (-1))!! 1)+1)) == '*' = (power xs ((basic xs i (-1))!! 0)) * (power xs ((basic xs (i+2) (-1))!! 0))
     | (xs !! (((basic xs i (-1))!! 1)+1)) == '/' = (power xs ((basic xs i (-1))!! 0)) `div` (power xs ((basic xs (i+2) (-1))!! 0))
     |otherwise = power xs i


power :: [Char] -> Int -> Int 
power xs i
    | (xs !! (((basic xs i (-1))!! 1)+ 1)) == '^' = (((basic xs i (-1))!! 0) ^ ((basic xs (i+2) (-1))!! 0))
    |otherwise = (basic xs i (-1)) !! 0


basic :: [Char] -> Int -> Int -> [Int]
basic xs i pnum 
    | pnum > (-1) && (isDigit(xs !!(i+1))) = basic xs (i+1) (pnum*10 + (digitToInt(xs !! i)))
    | isDigit(xs !! i ) && isDigit(xs !!(i+1)) = basic xs (i+1) (digitToInt (xs !! i))
    | pnum > (-1) && not (isDigit(xs !!(i+1))) = [pnum, i] -- + digitToInt(xs !! i)
    | xs !! i == '-' = [(-(basic xs (i+1)(-1)) !! 0) , i] -- may want to delete if add/sub can handle
    | xs !! i == '(' = [(expression xs (i+1)), i]
    | xs !! i == ')' = [(expression xs (i+1)), i] --This may not work here
    | otherwise =  [digitToInt (xs !! i), i]

0 个答案:

没有答案