aboutsummaryrefslogtreecommitdiff
path: root/discocaml/eval.ml
blob: a5cfe416c8bf70a794ded7e9cec28db643e5bbd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
open Ast

let or_else (type a) (l : a option) (r : a option Lazy.t) : a option =
  match l with Some x -> Some x | None -> Lazy.force r

let is_redex (ast : expr ast) (i : expr index) : bool =
  match get_subexpr ast i with
  | App (f, _) -> (
      match get_subexpr ast f with Lam (_, _) -> true | _ -> false)
  | Int _ -> false
  | Lam (_, _) -> false
  | Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) -> (
      match (get_subexpr ast l, get_subexpr ast r) with
      | Int _, Int _ -> true
      | _ -> false)
  | Var _ -> false

let find_redex_cbv_in (ast : expr ast) : expr index -> expr index option =
  let rec loop (i : expr index) : expr index option =
    or_else
      (match get_subexpr ast i with
      | App (f, x) -> or_else (loop f) (lazy (loop x))
      | Int _ -> None
      | Lam (_, _) -> None
      | Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) ->
          or_else (loop l) (lazy (loop r))
      | Var _ -> None)
      (lazy (if is_redex ast i then Some i else None))
  in
  loop

let find_redex_cbn_in (ast : expr ast) : expr index -> expr index option =
  let rec loop (i : expr index) : expr index option =
    if is_redex ast i then Some i
    else
      match get_subexpr ast i with
      | App (f, x) -> or_else (loop f) (lazy (loop x))
      | Int _ -> None
      | Lam (_, _) -> None
      | Prim (Add, (l, r)) | Prim (Sub, (l, r)) | Prim (Mul, (l, r)) ->
          or_else (loop l) (lazy (loop r))
      | Var _ -> None
  in
  loop

let find_redex_cbv (ast : expr ast) : expr index option =
  find_redex_cbv_in ast ast.root

let find_redex_cbn (ast : expr ast) : expr index option =
  find_redex_cbn_in ast ast.root

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