Intro
Example d’interpréteur en OCaml
let eval expr =
let lst = String.split_on_char ' ' expr in
let cmd = List.hd lst in (* hd = head *)
let args = List.map int_of_string (List.tl lst) in
match cmd with
| "num" -> Some (List.hd args)
| "add" -> Some ((List.nth args 0) + (List.nth args 1))
| "exit" -> None
| _ ->
Printf.eprintf "Error: unknown command '%s' \n" cmd ;
None
let rec repl invite =
print_string invite ;
match read_line () |> eval_with
| Some n -> Printf.printf "%d\n" n ;
repl invite
| None -> Printf.eprintf "Bye.\n"
let () = repl "> "
Example d’une implémentation de
map
en OCaml
let rec_map f l =
match l with
| [] -> []
(* tl = tail *)
| hd :: tl -> (f hd) :: (map f tl)
ratio
exception UnknownCmd of string
let to_python expr =
let lst = String.split on_char ' ' expr in
let cmd = List.hd lst in
let args = List.map int_of_string (List.tl lst) in
match cmd with
| "num" -> Printf.sprintf "print(%d)" (List.hd args)
| "add" -> Printf.sprintf "print(%d)" ((List.hd args) + (List.nth args 1))
| "exit" -> Printf.sprintf "exit(1)"
| _ -> raise (UnknownCmd)
let compile ic_oc =
let rec comp l =
try
let expr = input_line ic in
Printf.fprintf oc "%s\n" (to_python expr) ;
comp (l + 1)
with
| End_of_file -> ()
| UnknownCmd c -> (* J'ai pas fini de recopié RIP x( *)
Projet marrant qui partent de NAND pour faire quelque chose de plus cool :
- Nand2Tetris
- Nand2Raytracer
- Ben Eater (youtube)
Utiliser son language comme compilateur du language ça permet de manger sa propore merde