Last active
October 14, 2015 15:53
-
-
Save camlspotter/6c8a70ddd2b5fce04d6a to your computer and use it in GitHub Desktop.
How fib is compiled in OCaml, and a hand compilation of it to Elisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let rec fib = function | 0 -> 0 | 1 -> 1 | n -> fib (n-1) + fib (n-2) | |
(* Output of -dlambda *) | |
(setglobal Fib! | |
(letrec | |
(fib/1008 | |
(function n/1009 | |
(if (!= n/1009 0) | |
(if (!= n/1009 1) | |
(+ (apply fib/1008 (- n/1009 1)) (apply fib/1008 (- n/1009 2))) | |
1) | |
0))) | |
(makeblock 0 fib/1008))) | |
(* Actual OCaml data of lambda *) | |
Lprim | |
(Psetglobal ("Fib_0"), | |
[ Lletrec | |
([ ("fib_1008", | |
Lfunction | |
(Curried, [ "n_1009" ], | |
Lifthenelse | |
(Lprim | |
(Pintcomp (Cneq), | |
[ Lvar ("n_1009"); Lconst (Const_base (Const_int (0))) ]), | |
Lifthenelse | |
(Lprim | |
(Pintcomp (Cneq), | |
[ Lvar ("n_1009"); Lconst (Const_base (Const_int (1))) ]), | |
Lprim | |
(Paddint, | |
[ Lapply | |
(Lvar ("fib_1008"), | |
[ Lprim | |
(Psubint, | |
[ Lvar ("n_1009"); | |
Lconst (Const_base (Const_int (1))) ]) ], | |
"File \"fib.ml\", line 4, characters 9-18"); | |
Lapply | |
(Lvar ("fib_1008"), | |
[ Lprim | |
(Psubint, | |
[ Lvar ("n_1009"); | |
Lconst (Const_base (Const_int (2))) ]) ], | |
"File \"fib.ml\", line 4, characters 21-30") ]), | |
Lconst (Const_base (Const_int (1)))), | |
Lconst (Const_base (Const_int (0)))))) ], | |
Lprim (Pmakeblock (0, Immutable), [ Lvar ("fib_1008") ])) ]) | |
(* Hand compilation to Elisp *) | |
(setq fib/1008 (lambda (n/1009) | |
(if (not (equal n/1009 0)) | |
(if (not (equal n/1009 1)) | |
(+ (funcall fib/1008 (- n/1009 1)) | |
(funcall fib/1008 (- n/1009 2))) | |
1) | |
0))) | |
(defun fib/1008/f (n) (funcall fib/1008 n)) | |
(fib/1008/f 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment