This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,4 @@
(define (factorial n)
(if (<= n 0)
1
(* n (factorial (- n 1)))))

View file

@ -0,0 +1,6 @@
(define (factorial n)
(let loop ((i 1)
(accum 1))
(if (> i n)
accum
(loop (+ i 1) (* accum i)))))

View file

@ -0,0 +1,4 @@
(define (factorial n)
(do ((i 1 (+ i 1))
(accum 1 (* accum i)))
((> i n) accum)))

View file

@ -0,0 +1,23 @@
;Using a generator and a function that apply generated values to a function taking two arguments
;A generator knows commands 'next? and 'next
(define (range a b)
(let ((k a))
(lambda (msg)
(cond
((eq? msg 'next?) (<= k b))
((eq? msg 'next)
(cond
((<= k b) (set! k (+ k 1)) (- k 1))
(else 'nothing-left)))))))
;Similar to List.fold_left in OCaml, but uses a generator
(define (fold fun a gen)
(let aux ((a a))
(if (gen 'next?) (aux (fun a (gen 'next))) a)))
;Now the factorial function
(define (factorial n) (fold * 1 (range 1 n)))
(factorial 8)
;40320