我正在编写一个基本的Haskell解释器,并且有以下用例: 有两个变量,var1和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;
如何在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 :(得分:2)
我没有Val
的定义,所以我必须在这里猜测:
case (valLhs, valRhs) of
(IntVal i1, IntVal i2) -> IntVal $ i1 + i2
(StringVal s1, StringVar s2) -> ...
答案 1 :(得分: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