#lang racket #| Max Sherman CSE 341 Section 02 Things to do: 1. Go over homework 1 2. Binary tree (structs, mutation) 3. Loops (macros, mutation) 4. Streams (delayed evaluation) |# ;; A macro to emulate a while loop. (define-syntax while (syntax-rules (do) ([while test do body ...] [letrec ([loop (lambda () (when test body ... (loop)))]) (loop)]))) ;; To calculate the sum from 1 to 10 call (sum-n 10), and then the result is ;; stored in ans (define ans 0) (define (sum-n n) (while (positive? n) do (set! ans (+ n ans)) (set! n (sub1 n)))) (struct node (n l r) #:transparent) ;; An "object" representing a sorted binary tree. ;; Example calls: ;; (define t (make-sorted-bin-tree)) ;; ((t 'add) 5) ;; ((t 'add) 1) ;; ((t 'contains?) 5) ;; ((t 'get)) (define (make-sorted-bin-tree) (let ([root null]) (define (dispatch m) (cond [(eq? m 'contains?) contains?] [(eq? m 'add) add] [(eq? m 'get) get] [else (error "unsupported")])) (define (add n) (letrec ([add* (lambda (t n) (cond [(null? t) (node n null null)] [(< n (node-n t)) (node (node-n t) (add* (node-l t) n) (node-r t))] [else (node (node-n t) (node-l t) (add* (node-r t) n))]))]) (set! root (add* root n)))) (define (contains? n) (letrec ([contains* (lambda (t n) (cond [(null? t) #f] [(= n (node-n t)) #t] [(< n (node-n t)) (contains* (node-l t) n)] [else (contains* (node-r t) n)]))]) (contains* root n))) (define (get) root) dispatch)) ;; Streams. ;; Natural numbers (define nats (letrec ([helper (lambda (n) (cons n (lambda () (helper (add1 n)))))]) (lambda () (helper 0)))) ;; Infinitely print things in the stream. (define (do-it pr) (displayln (car pr)) (do-it ((cdr pr)))) ;; List iterator. (define (iter lst) (cons (car lst) (lambda () ((iter (cdr lst))))))