open Ast 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) | _ -> ()) | Int _ -> () | 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) | _ -> ()) | Var _ -> () let find_redex_cbv_in (ast : expr ast) : expr index -> unit = let rec loop (i : expr index) : unit = (match get_subexpr ast i with | App (f, x) -> loop f; loop x | Int _ -> () | Lam (_, _) -> () | Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) -> loop l; loop r | Var _ -> ()); check_redex ast i in loop let find_redex_cbn_in (ast : expr ast) : expr index -> unit = let rec loop (i : expr index) : unit = check_redex ast i; match get_subexpr ast i with | App (f, x) -> loop f; loop x | Int _ -> () | Lam (_, _) -> () | Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) -> loop l; loop r | Var _ -> () in loop let find_redex_cbv (ast : expr ast) : expr index option = try find_redex_cbv_in ast ast.root; None with FoundRedex i -> Some i let find_redex_cbn (ast : expr ast) : expr index option = try find_redex_cbn_in ast ast.root; None with FoundRedex i -> Some i exception NotARedex of expr ast 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" | 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) | _ -> fail ()); ast