making types: Add data type and evaluator that is of an unmatched type

霸气de小男生 提交于 2020-12-15 01:38:42

问题


I have added | Lit Int and | Add Exp Exp to the data type as seen below, along with the evaluation. However I get an error "Couldn't match expected type ‘Var’ with actual type ‘Int’".

data Exp = V Var
    | B Bool
    | L Exp
    | A Exp Exp
    | Lit Int
    | Add Exp Exp
data Var = VZ |VS Var

eval:: Exp -> Var
eval (Lit n)     = n
eval (Add e1 e2) = eval e1 + eval e2

How can I add Int and Add to the data type, along with the evaluation, but maintain the following code as is. Is this possible?

data Exp = V Var
    | B Bool
    | L Exp
    | A Exp Exp
data Var = VZ |VS Var

I have added an instance to resolve this, as seen below, but now I have the error "Pattern bindings (except simple variables) not allowed in instance declaration: Add e1 e2 = (Lit e1) + (Lit e2)":

{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}

data Exp = V Var
    | B Bool
    | L Exp
    | A Exp Exp
    | Lit Int
    | Add Exp Exp
data Var = VZ |VS Var

eval:: Exp -> Var
eval (Lit n)     = n
eval (Add e1 e2) = eval e1 + eval e2

instance Num Var where
    Lit e = e

instance Num Var where
    Add e1 e2 = (Lit e1) + (Lit e2)

回答1:


You seem to have gotten mixed up along the way. I believe Var represents a free variable in De Bruijn notation. You're missing an encoding of values. This could look something vaguely like

data Value
  = IntVal !Int
  | BoolVal !Bool
  | Closure { environment :: [Value]
            , expr :: Exp }

Now you'll want eval :: Exp -> Value to evaluate expressions. There's lots of work left.



来源:https://stackoverflow.com/questions/64525927/making-types-add-data-type-and-evaluator-that-is-of-an-unmatched-type

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