Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,18 @@
#lang racket
;; Natural -> Natural
;; Calculate factorial
(define (fact n)
(define (fact-helper n acc)
(if (= n 0)
acc
(fact-helper (sub1 n) (* n acc))))
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'fact "natural" n))
(fact-helper n 1))
;; Unit tests, works in v5.3 and newer
(module+ test
(require rackunit)
(check-equal? (fact 0) 1)
(check-equal? (fact 5) 120))

View file

@ -0,0 +1,20 @@
#lang racket
;; Natural -> Natural
;; Calculate fibonacci
(define (fibb n)
(define (fibb-helper n fibb_n-1 fibb_n-2)
(if (= 1 n)
fibb_n-1
(fibb-helper (sub1 n) (+ fibb_n-1 fibb_n-2) fibb_n-1)))
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'fibb "natural" n))
(if (zero? n) 0 (fibb-helper n 1 0)))
;; Unit tests, works in v5.3 and newer
(module+ test
(require rackunit)
(check-exn exn:fail? (lambda () (fibb -2)))
(check-equal?
(for/list ([i (in-range 21)]) (fibb i))
'(0 1 1 2 3 5 8 13 21 34 55 89 144 233
377 610 987 1597 2584 4181 6765)))

View file

@ -0,0 +1,14 @@
#lang racket
;; We use Z combinator (applicative order fixed-point operator)
(define Z
(λ (f)
((λ (x) (f (λ (g) ((x x) g))))
(λ (x) (f (λ (g) ((x x) g)))))))
(define fibonacci
(Z (λ (fibo)
(λ (n)
(if (<= n 2)
1
(+ (fibo (- n 1))
(fibo (- n 2))))))))