;; The first three lines of this file were inserted by DrScheme. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-advanced-reader.ss" "lang")((modname change_memory) (read-case-sensitive #t) (teachpacks ((lib "testing.ss" "teachpack" "htdp") (lib "draw.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "testing.ss" "teachpack" "htdp") (lib "draw.ss" "teachpack" "htdp"))))) ;; redefining a variable (define x 5) (set! x 6) ;; it's an operation, the result of it is a special ;; value "void" x ;; a sequence of operations ;; note: only the last one can be non-void (define y 2) (begin (set! y (+ x 2)) (set! x (+ y 2)) (+ x y)) "x = " x "y = " y ;; note that keeping track of variables is now much harder ;; for this reason use of memory updates should be limited ;; Address book example: a "global" address-book (define address-book empty) ;; lookup : symbol (listof (list symbol number)) -> number or false ;; to lookup the phone number for name in ab (define (lookup name ab) (cond [(empty? ab) false] [else (cond [(symbol=? (first (first ab)) name) (second (first ab))] [else (lookup name (rest ab))])])) ;; add-to-address-book : symbol number -> void (define (add-to-address-book name phone) (set! address-book (cons (list name phone) address-book))) (add-to-address-book 'Sally 1234567) address-book (add-to-address-book 'Peter 9876543) address-book ;; changing structures (define-struct phone-entry (name phone)) (define address-book2 (list (make-phone-entry 'Sally 1234567) (make-phone-entry 'Peter 9876543))) address-book2 ;; symbol number address-book -> void ;; Goven a name and a number, updates the phone number ;; for that name to the number in the address book (define (update-phone name phone ab) (cond [(empty? ab) (error 'update-phone! "no such phone")] [(symbol=? name (phone-entry-name (first ab))) (set-phone-entry-phone! (first ab) phone)] [else (update-phone name phone (rest ab))] ) ) (update-phone 'Sally 2345678 address-book2) address-book2 (update-phone 'Peter 8765432 address-book2) address-book2 ;; counting even numbers with a global counter (define evens 0) ;; lon -> void ;; counts the number of even elements by updating a global counter (define (count-evens lon) (cond [(empty? lon) false] [(even? (first lon)) (begin (set! evens (+ evens 1)) (count-evens (rest lon)))] [else (count-evens (rest lon))] ) ) (count-evens (list 1 2 3 4 5 6 7 8)) "Evens:" evens