可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm writing a basic Haskell interpreter and there is the following usecase: there are 2 variables, var1 and var2.
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;
How can I write it in Haskell?
There's a part of the code:
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....
回答1:
I don't have the definition of Val
, so I have to guess here:
case (valLhs, valRhs) of (IntVal i1, IntVal i2) -> IntVal $ i1 + i2 (StringVal s1, StringVar s2) -> ...
回答2:
Here's an example of mixed types being evaluated using simple pattern-matching. It's not an exact answer to your question, but maybe it'll help you.
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