3 ms·
For whatever it's worth, here is the same in 24 lines of OCaml: type cell = Atom of string | Sexpr of cell list let library = Hashtbl.cr
by tom_mellior 8y ago
For whatever it's worth, here is the same in 24 lines of OCaml:
type cell = Atom of string
| Sexpr of cell list
let library = Hashtbl.create 1
let rec eval = function
| Atom s -> s
| Sexpr [] -> failwith "Empty sexpr"
| Sexpr (head :: args) ->
let fname = eval head in
match Hashtbl.find_opt library fname with
| Some builtin -> builtin args
| None -> failwith (String.concat " " [fname; " not found"])
let main () =
let prog = Sexpr [Atom "cat"; Atom "Hello "; Atom "world!"] in
let prog2 = Sexpr [Sexpr [Atom "cat"; Atom "c"; Atom "a"; Atom "t"];
Atom "Hello "; Atom "world!"] in
Hashtbl.add library "cat"
(fun args -> String.concat "" (List.map eval args));
Printf.printf "%s\n" (eval prog);
Printf.printf "%s\n" (eval prog2)
let _ = main ()
Using linked lists instead of vectors makes separating an application's head and args (CAR and CDR, if you prefer) much easier than using clunky C++ iterators. This is because linked list cells are composed of cons cells.