简体   繁体   中英

Check the type of a variable in Haskell script

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....

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) -> ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM