ocaml: phase 5.1 lambda_calc.ml baseline (17/17 pass)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
Untyped lambda calculus interpreter inside OCaml-on-SX: type term = Var | Abs of string * term | App | Num of int type value = VNum of int | VClos of string * term * env let rec eval env t = match t with ... (\x.\y.x) 7 99 = 7. The substrate handles two ADTs, recursive eval, closure-based env, and pattern matching all written as a single self-contained OCaml program — strong validation.
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
"factorial.ml": 3628800,
|
||||
"fizzbuzz.ml": 57,
|
||||
"list_ops.ml": 30,
|
||||
"lambda_calc.ml": 7,
|
||||
"memo_fib.ml": 75025,
|
||||
"module_use.ml": 3,
|
||||
"mutable_record.ml": 10,
|
||||
|
||||
41
lib/ocaml/baseline/lambda_calc.ml
Normal file
41
lib/ocaml/baseline/lambda_calc.ml
Normal file
@@ -0,0 +1,41 @@
|
||||
(* Baseline: untyped lambda calculus with closures over a Hashtbl env *)
|
||||
type term =
|
||||
| Var of string
|
||||
| Abs of string * term
|
||||
| App of term * term
|
||||
| Num of int
|
||||
;;
|
||||
|
||||
type value =
|
||||
| VNum of int
|
||||
| VClos of string * term * (string * value) list
|
||||
;;
|
||||
|
||||
let rec lookup name env =
|
||||
match env with
|
||||
| [] -> failwith "unbound"
|
||||
| (n, v) :: t -> if n = name then v else lookup name t
|
||||
;;
|
||||
|
||||
let rec eval env t =
|
||||
match t with
|
||||
| Num n -> VNum n
|
||||
| Var x -> lookup x env
|
||||
| Abs (x, body) -> VClos (x, body, env)
|
||||
| App (f, a) ->
|
||||
let fv = eval env f in
|
||||
let av = eval env a in
|
||||
(match fv with
|
||||
| VClos (param, body, captured) ->
|
||||
eval ((param, av) :: captured) body
|
||||
| _ -> failwith "not a function")
|
||||
;;
|
||||
|
||||
let unwrap v = match v with VNum n -> n | _ -> failwith "not a number" ;;
|
||||
|
||||
(* (\x. \y. x) 7 99 = 7 *)
|
||||
let term =
|
||||
App (App (Abs ("x", Abs ("y", Var "x")), Num 7), Num 99)
|
||||
;;
|
||||
|
||||
unwrap (eval [] term)
|
||||
Reference in New Issue
Block a user