2017-10-05 37 views
0

嗨我需要計算類型的幫助。整個程序假設要一個字符串,解析它,最後計算一個值。我開始的字符串可以是這樣的:「let X = + 1 2 in * X 2 - X」。當我解析它時,我會得到這個:「Let (Vari X) (Sum (Lit 1) (Lit 2)) (Mul (Vari X) (Lit 2)))」。此時,我可以解析像這樣的「* + 2 3 * 2 + 6 - 2」和之前的表達式。但我無法計算出前面的表達式,「let X = + 1 2 in * X 2 - X」。如果有人能指引我朝着正確的方向發展,我會很高興,因爲現在,我真的不知道我會如何做這項工作。由於Haskell - 計算字符串「讓X = 3 in + X X」

代碼:

data Chara = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z deriving (Eq, Show) 

data Number = Single Int | Many Int Number deriving (Eq, Show) 

data Expr = Lit Int | Sub Expr | Sum Expr Expr | Mul Expr Expr | Vari Chara | Let Expr Expr Expr 
    deriving Show 


--Want to calculate this 
--Let (Vari X) (Sum (Lit 1) (Lit 2)) (Mul (Vari X) (Lit 2))) 


calculate :: Expr -> Int 
calculate (Sub a) = let e = calculate a in (-e) 
calculate (Sum a b) = let e = calculate a 
          r = calculate b 
         in (e+r)   
calculate (Mul a b) = let e = calculate a 
          r = calculate b 
         in (e*r) 
calculate (Lit a) = a  
+0

你肯定應該'讓Expr的Expr的Expr'而不是'讓甜心Expr的Expr'? (並不是說這是完全不合理的,但它有點棘手,可能不值得在教育方面)。 – leftaroundabout

+0

是否[你們](https://stackoverflow.com/questions/46584907/haskell-parsing-input-functions)獲得同一班級的作業? –

+0

我正在做一項任務。不知道其他人。 – iIllumination

回答

1

您需要在您的AST執行變量替換。即您需要一個函數

substitute :: (Chara, Expr) -> Expr -> Expr 

其中,給定的一對變量的替代表達來代替它會遍歷樹,並執行替換。這基本上意味着:如果您發現一個Vari,只需用替換替換它。如果您發現像Sum a b子表達式什麼,遞歸下降到這些子表達式,然後重建操作的結果,即

 Sum (substitute s a) (substitute s b) 

然後calculate (Let var subst expr) = ...substitute功能的一個非常簡單的調用。

+0

謝謝!我想我得到了一些開始工作的東西! :d – iIllumination

1

就像一個魅力

calculate :: Expr -> Int 
calculate (Sub a) = let e = calculate a in (-e) 
calculate (Sum a b) = let e = calculate a 
          r = calculate b 
         in (e+r)   
calculate (Mul a b) = let e = calculate a 
          r = calculate b 
         in (e*r) 
calculate (Let a b c) = calculate (substitute (getCharaFromExpr a) b c) 
calculate (Lit a) = a  


substitute :: Chara -> Expr -> Expr -> Expr 
substitute x y (Lit a) = Lit a 
substitute x y (Vari a) | x == a = y 
         | otherwise = Vari a 
substitute x y (Sum a b) = Sum (substitute x y a) (substitute x y b) 
substitute x y (Mul a b) = Mul (substitute x y a) (substitute x y b) 
substitute x y (Sub a) = Sub (substitute x y a) 
substitute x y (Let a b c) = Let (substitute x y a) (substitute x y b) (substitute x y c)