2015-10-29 50 views
0

我正在編寫一個基本的Haskell解釋器,並且有以下用例: 有2個變量,var1和var2。檢查Haskell腳本中的變量的類型

if((typeOf var1 is Integer) and (typeOf var2 is Integer)) then var1 + var2; 

if((typeOf var1 is String) and (typeOf var2 is String)) then concatenate var1 to var2; 

如何在Haskell中編寫它?

有代碼的一部分:

evaluate:: Expr -> Env -> Val 
evaluate expr env = 
    trace("expr= " ++ (show expr) ++ "\n env= " ++ (show env)) $ 
    case expr of 
    Const v -> v 
    lhs :+: rhs -> 
    let valLhs = evaluate lhs env 
     valRhs = evaluate rhs env 
    in case() of 
    _ | <both are Integer> ->(IntVal $ (valToInteger valLhs) + (valToInteger valRhs)) 
     | <both are String> -> (StringVal $ (valToString valLhs) ++ (valToString valRhs)) 
     | otherwise.... 
+0

什麼是'Expr','Env'和'Val'? – bheklilr

+0

您正在使用大量退款括號。 –

回答

2

我沒有的Val的定義,所以我猜這裏:

case (valLhs, valRhs) of 
    (IntVal i1, IntVal i2)  -> IntVal $ i1 + i2 
    (StringVal s1, StringVar s2) -> ... 
1

這裏是正在評估混合類型的例子使用簡單的模式匹配。這不是你的問題的確切答案,但也許它會幫助你。

data Expr a = I Int 
      | S String 
      | V a 
      | Plus (Expr a) (Expr a) 
      deriving (Show) 

type Env a = a -> Maybe (Expr a) 

eval :: Env a -> Expr a -> Expr a 
eval _ (I x) = I x 
eval _ (S s) = S s 
eval _ (Plus (I x) (I y)) = I (x + y) 
eval _ (Plus (S x) (S y)) = S (x ++ y) 
eval e (Plus (V v) y) = eval e (Plus (eval e (V v)) y) 
eval e (Plus x (V v)) = eval e (Plus x (eval e (V v))) 
eval _ (Plus _ _) = undefined 
eval e (V v) = case e v of Just x -> x 
          Nothing -> undefined 

env :: Char -> Maybe (Expr Char) 
env 'a' = Just (I 7) 
env 'b' = Just (I 5) 
env 'c' = Just (S "foo") 
env 'd' = Just (S "bar") 
env _ = Nothing