;; A Chain is a class with two methods ;; that represents an immutable chain of objects. ;; getLength: --> number, which returns the length of the chain ;; getNext: --> Chain, which returns a new Chain that is one longer ;; and linked to this Chain. (define-struct Chain (getLength getNext)) ;; A zero length Chain (define chain0 (local [;; chainFactory: Chain --> Chain ;; An internal factory to enable recursive self-generation ;; parent is the previous Chain the new Chain links to. ;; This is the inductive generation process (define (chainFactory parent) (local [(define newChain ;; for self reference (make-Chain (lambda () ;; recursively calculate the length (+ 1 ((Chain-getLength parent)))) (lambda () ;; recursively self generate using the factory (chainFactory newChain))))] newChain)) ;; return the new chain (define this ;; for self reference (make-Chain (lambda () ;; base case chain has length zero 0) (lambda () ;; recursively self-generate using the factory (chainFactory this))))] this)) ;; return the base case chain "Chain test cases:" (= 0 ((Chain-getLength chain0))) (define chain1 ((Chain-getNext chain0))) (= 1 ((Chain-getLength chain1))) (define chain2 ((Chain-getNext chain1))) (= 2 ((Chain-getLength chain2))) (define chain3 ((Chain-getNext chain2))) (= 3 ((Chain-getLength chain3))) ;;addNChain: Chain natnum --> Chain ;; Adds n chains to a-chain. (define (addNChain a-chain n) (cond [(zero? n) a-chain] [(< 0 n) (addNChain ((Chain-getNext a-chain)) (sub1 n))])) "AddNChain test cases:" (define chain25 (addNChain chain0 25)) (= 25 ((Chain-getLength chain25))) (= 40 ((Chain-getLength (addNChain chain25 15))))