aboutsummaryrefslogtreecommitdiff
path: root/discocaml/eval.ml
diff options
context:
space:
mode:
Diffstat (limited to 'discocaml/eval.ml')
-rw-r--r--discocaml/eval.ml38
1 files changed, 31 insertions, 7 deletions
diff --git a/discocaml/eval.ml b/discocaml/eval.ml
index aa90d41..5e2cae4 100644
--- a/discocaml/eval.ml
+++ b/discocaml/eval.ml
@@ -5,11 +5,9 @@ exception FoundRedex of expr index
let check_redex (ast : expr ast) (i : expr index) : unit =
match get_subexpr ast i with
| App (f, _) -> (
- match get_subexpr ast f with
- | Lam (_, _) -> raise (FoundRedex i)
- | _ -> ())
+ match get_subexpr ast f with Lam _ -> raise (FoundRedex i) | _ -> ())
| Int _ -> ()
- | Lam (_, _) -> ()
+ | Lam _ -> ()
| Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) -> (
match (get_subexpr ast l, get_subexpr ast r) with
| Int _, Int _ -> raise (FoundRedex i)
@@ -23,7 +21,7 @@ let find_redex_cbv_in (ast : expr ast) : expr index -> unit =
loop f;
loop x
| Int _ -> ()
- | Lam (_, _) -> ()
+ | Lam _ -> ()
| Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) ->
loop l;
loop r
@@ -40,7 +38,7 @@ let find_redex_cbn_in (ast : expr ast) : expr index -> unit =
loop f;
loop x
| Int _ -> ()
- | Lam (_, _) -> ()
+ | Lam _ -> ()
| Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) ->
loop l;
loop r
@@ -62,13 +60,39 @@ let find_redex_cbn (ast : expr ast) : expr index option =
exception NotARedex of expr ast
+let subst (ast : expr ast) (from : string) (to_ : expr index) :
+ expr index -> expr index =
+ let rec loop (i : expr index) : expr index =
+ let add (expr : expr) : expr index =
+ if get_subexpr ast i = expr then i
+ else
+ let index = Arraylist.length ast.subexprs in
+ Arraylist.push ast.subexprs expr;
+ { index }
+ in
+ match get_subexpr ast i with
+ | App (f, x) ->
+ let f' = loop f and x' = loop x in
+ add (App (f', x'))
+ | Int _ -> i
+ | Lam (x, b) -> if String.equal from x then i else add (Lam (x, loop b))
+ | Prim (Add, (l, r)) -> add (Prim (Add, (loop l, loop r)))
+ | Prim (Sub, (l, r)) -> add (Prim (Sub, (loop l, loop r)))
+ | Prim (Mul, (l, r)) -> add (Prim (Mul, (loop l, loop r)))
+ | Var x -> if String.equal from x then to_ else i
+ in
+ loop
+
let reduce (ast : expr ast) (i : expr index) : expr ast =
let fail () = raise (NotARedex { ast with root = i }) in
let ast = copy ast in
let must_int j = match get_subexpr ast j with Int n -> n | _ -> fail () in
Arraylist.set ast.subexprs i.index
(match get_subexpr ast i with
- | App (_f, _x) -> failwith "TODO"
+ | App (f, x) -> (
+ match get_subexpr ast f with
+ | Lam (x', b) -> get_subexpr ast (subst ast x' x b)
+ | _ -> fail ())
| Prim (Add, (l, r)) -> Int (must_int l + must_int r)
| Prim (Sub, (l, r)) -> Int (must_int l - must_int r)
| Prim (Mul, (l, r)) -> Int (must_int l * must_int r)