Check the type of a variable in Haskell script

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!