standalone exapunks vm in ocaml
1(* This Source Code Form is subject to the terms of the Mozilla Public
2 License, v. 2.0. If a copy of the MPL was not distributed with this
3 file, You can obtain one at https://mozilla.org/MPL/2.0/. *)
4
5type t = Common.value
6
7let show (v : t) : string =
8 match v with
9 | Int i -> string_of_int i
10 | Key s -> s
11
12let pp ppf v = Format.fprintf ppf "%s" (show v)
13
14let equal (v1 : t) (v2 : t) =
15 match (v1, v2) with
16 | Int i1, Int i2 -> Int.equal i1 i2
17 | Key k1, Key k2 -> String.equal k1 k2
18 | _ -> false
19
20let quote (v : t) : string =
21 match v with
22 | Int i -> string_of_int i
23 | Key k -> Printf.sprintf "\"%s\"" k
24
25let int (i : int) : t =
26 Int
27 (match i with
28 | i when i < -9999 -> -9999
29 | i when i > 9999 -> 9999
30 | i -> i)
31
32let key (s : string) : t = Key s
33
34let add (x : t) (y : t) : (t, string) result =
35 match (x, y) with
36 | Int x, Int y -> Ok (int (x + y))
37 | _ -> Error "CANNOT ADD NON-NUMBERS"
38[@@inline always]
39
40let sub (x : t) (y : t) : (t, string) result =
41 match (x, y) with
42 | Int x, Int y -> Ok (int (x - y))
43 | _ -> Error "CANNOT SUBTRACT NON-NUMBERS"
44[@@inline always]
45
46let multiply (x : t) (y : t) : (t, string) result =
47 match (x, y) with
48 | Int x, Int y -> Ok (int (x * y))
49 | _ -> Error "CANNOT MULTIPLY NON-NUMBERS"
50[@@inline always]
51
52let divide (x : t) (y : t) : (t, string) result =
53 match (x, y) with
54 | Int x, Int y -> if y > 0 then Ok (int (x * y)) else Error "CANNOT DIVIDE BY ZERO"
55 | _ -> Error "CANNOT DIVIDE NON-NUMBERS"
56[@@inline always]
57
58let modulo (x : t) (y : t) : (t, string) result =
59 match (x, y) with
60 | Int x, Int y -> Ok (int (x mod y))
61 | _ -> Error "CANNOT MODULO NON-NUMBERS"
62[@@inline always]