Last active
September 28, 2017 22:12
-
-
Save christianromney/0b43f0896d927b1ea0d6588479a39ba2 to your computer and use it in GitHub Desktop.
Factorial 3 ways
This file contains hidden or 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
;; factorial (recursive) | |
(define fact | |
(lambda (n) | |
(if (= n 0) | |
1 | |
(* n (fact (- n 1)))))) | |
(display (fact 5)) ;; => 120 | |
(newline) | |
;; factorial (iterative) | |
(define facti | |
(lambda (x i) | |
(if (= x 0) | |
i | |
(facti (- x 1) (* x i))))) | |
(display (facti 5 1)) ;; => 120 | |
(newline) | |
;; factorial (continuation passing style) | |
(define factc | |
(lambda (n c) | |
(if (= n 0) | |
(c 1) | |
(factc (- n 1) | |
(lambda (a) (c (* n a))))))) | |
(display (factc 5 (lambda (x) x))) ;; => 120 | |
(newline) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment