So in the course I’m taking we’re trying to write an interpreter in f#. And for this we have to make a small calculator.
For this I was handed out this code:
type Value = INT of int
type Binop = BPLUS | BMINUS | BTIMES
type Rop = RSUM | RPROD | RMAX | RARGMAX
type vname = string
type Exp =
| CONSTANT of Value
| VARIABLE of vname
| OPERATE of Binop * Exp * Exp
| LET_IN of vname * Exp * Exp
| OVER_LIST of Rop * Exp list //must be non-empty
| OVER_RANGE of Rop * vname * Exp * Exp * Exp
(* An association list mapping variable names to their values. *)
type SymTab = (vname * Value) list
(* Inserts a variable into the variable table. *)
let bind v k vtab = (v, k) :: vtab : SymTab
(* Look up the value of a variable. *)
let rec lookup v = function
| (v', k) :: vtab -> if v = v' then k else lookup v vtab
| _ -> failwith ("unbound variable: " + v)
(* EVALUATION *)
(*****************************************************
* TODO: Task 2: complete the definition of `eval`. You may also
* define any auxiliary functions as you see fit, to help express `eval`
* as cleanly and concisely as possible.
****************************************************)
(* The evaluation function. *)
let rec eval (vtab : SymTab) (e : Exp) : Value =
match e with
| CONSTANT n -> n
| VARIABLE v -> failwith "case for VARIABLE not handled"
Where we have to define variable and a couple of other functions ourselves.
For Variable my idea was to use pattern matching like they did during the lectures.
So something like this
| VARIABLE v ->
match lookup v vtab with
| Some x -> x
| None -> failwith "Unknown variable."
So if lookup gives a variable, I just return that and if it doesn’t I return an error saying it doesnt exist.
However when I do this I get
“This expression was expected to have type
‘Value’
but here has type
”a option’ “
Please don’t just write the solution but if you can give some hints as to why this is not working I would be very happy.
Andreas Thiemke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.