我有一個ocaml函數,其中我模式匹配幾個案例。我不斷收到一個類型錯誤,我看不出如何處理它。任何幫助,將不勝感激。這是我收到的錯誤消息:「文件」eval.ml「,第40行,字符18-35: 錯誤:此表達式具有類型Env.symEntry」。第40行是「讓L = binding_of ENV X在」爲什麼這種類型的錯誤一直在發生?
(* eval_expr: expr -> proc_state -> env -> store -> value *)
(* eval_expr: expr -> proc_state -> env -> store -> int *)
let rec eval_expr (expr:expr) (ps:proc_state) (env:environment) (store:store) : int = match expr with
Add (e1, e2) ->
let r1 = eval_expr e1 ps env store in
let r2 = eval_expr e2 ps env store in
r1 + r2
| Sub (e1, e2) ->
let r1 = eval_expr e1 ps env store in
let r2 = eval_expr e2 ps env store in
r1 - r2
| Mul (e1, e2) ->
let r1 = eval_expr e1 ps env store in
let r2 = eval_expr e2 ps env store in
r1 * r2
| Div (e1, e2) ->
let r1 = eval_expr e1 ps env store in
let r2 = eval_expr e2 ps env store in
r1/r2
| Neg (e1) ->
let r1 = eval_expr e1 ps env store in
r1 * -1
| IntConst i -> i
(* - variable reads: handle the Id constructor from expr.
use binding_of and
value_at *)
| Id(x) ->
let l = binding_of env x in
let i = value_at store l in i;;
下面是一些功能和類型我使用的代碼行:
module IntMap = Map.Make(struct type t = int let compare = compare end);;
type store = int IntMap.t;;
let value_at store loc = IntMap.find loc store;;
let insert_value store loc v = IntMap.add loc v store;;
let enter_scope env scope = scope::env;;
let exit_scope env = List.tl env;;
let current_scope env = List.hd env;;
type expr = (* Expressions in C-flat *)
(* int operations *)
Add of expr * expr
| Sub of expr * expr
| Mul of expr * expr
| Div of expr * expr
| Neg of expr
(* constants/variables *)
| Id of string
| IntConst of int
(* array/pointer operations *)
| At of expr * expr
| Deref of expr
| AddressOf of expr
(* function *)
| Call of string * expr list
(* pre- & post-increment *)
| Pre of expr
| Post of expr
;;
let binding_of env name =
let lookup name symTab = List.assoc name symTab in
try
lookup name (List.hd env)
with Not_found ->
lookup name (List.hd (List.tl env))
;;
我在「binding_of」的代碼中添加了請看它。 – user4789552
我正在尋找,但仍然沒有足夠的細節來查看範圍的類型。如果你只是通過第40行的子表達式的類型,你幾乎肯定會找出問題。作爲一個註釋,這個'binding_of'函數不會遍歷整個列表。它只在前兩個環境中看起來(在我看來)。 –