(50)% mzscheme Welcome to MzScheme version 299.100, Copyright (c) 2004-2005 PLT Scheme, Inc. > ;; scheme has several forms of equality built in: (= 4 5) ;; only works on numbers #f > (eq? 5 5) ;; constant-time equality check #t > (eq? 'foo 'foo) #t > (define x '(1 2 3)) > (eq? x x) #t > (eq? x '(1 2 3)) #f > ;;; equal? works on list (element by element) (equal? x '(1 2 3)) #t > ;;; defining equal? ourselves: (define (equal? x y) (cond ((atom? x) (eq? x y)) (else (and (equal? (car x) (car y)) (equal? (cdr x) (cdr y)))) )) > > (define (atom? x) (or (number? x) (symbol? x) (null? x))) > (equal? '(1 (2 3) 4) '(1 (2 3) 4)) #t > 0 0 > ;;; storing data for keyed lookups ;;; use an association list ("a-list") ;;;; list ((key1 value1) ... (keyN valueN)) '((name ben) (age 44) (salary 10)) ;; a personnel record ((name ben) (age 44) (salary 10)) > ;;; use (assoc key L) to lookup the key in L (assoc 'age '((name ben) (age 44) (salary 10))) (age 44) > (assoc 'spouse '((name ben) (age 44) (salary 10))) #f > ;;; write assoc ourselves: (define (assoc key L) (cond ((null? L) #f) ((equal? (car (car L)) key) (car L)) (else (assoc key (cdr L))))) > > (assoc 'age '((name ben) (age 44) (salary 10))) (age 44) > (define (make-account password balance) (lambda (op) (let ((passwd (begin (display "Enter Password") (newline) (read)))) (cond ((not (eq? password passwd)) (display "Incorrect Password") (newline)) (else (cond ((eq? op 'balance) (display "Balance is ") (display balance) (newline)) ((eq? op 'withdraw) (let ((amount (begin (display "Enter Amount") (newline) (read)))) (cond ((<= amount balance) (set! balance (- balance amount)) 'done) (else (display "Amount exceeds balance") (newline))))) ((eq? op 'deposit) (let ((amount (begin (display "Enter Amount") (newline) (read)))) (set! balance (+ balance amount)) 'done)) (else (display "Incorrect Operation") (newline)) ))) ))) > (define my-account (make-account 'ben 100)) > my-account # > (my-account 'balance) Enter Password ben Balance is 100 > (my-account 'withdraw) Enter Password ben Enter Amount 5 done > Enter Password ben Balance is 95 > (define your-account (make-account 'you 50)) > (your-account 'balance) Enter Password you Balance is 50 > > (define (f x) 3) > f # > (define (g y) (display y) (newline) (+ y 1)) > (g 7) 7 8 > ;;; apply applies a function to a list of arguments (apply + '(3 4)) 7 > > (apply car '((3 4))) 3 >