February 23, 2000 more on scheme....... Association lists ((obj val) (obj val) ..... ) (Assoc obj ALIST) obj is the key ex. (Define AL '((A 10) (B 20) (C 30))) (Assoc 'A AL) --> (A 10) (Assoc 'B AL) --> (B 20) (Assoc 'Z AL) --> #f (Define LI '(((BMW M3) 40270) ((BMW 740) 62070) ((Jag xJ8) 55330) ........ ((BMW 540 automatic))) -- not all have to be the same type (Assoc '(Jag xJ8) LI)) --> 55330 using association lists -- is the key in alist? (define (structure key alist); version 1 of struct (if (assoc key alist) (car (cdr (assoc key alist))) #f ) ) -- revised version, more efficient (define (structure key alist) (let ( (p (assoc key alist))) (if p (cadr p) #f ) ) ) -- editing the association list (define (set-struct key alist val) (cons (list key val) alist)) --risky, cause you're changing a shared value -- ! aka a shriek, lets the user know that a parameter is -- being changed (define (set-struct! key alist val) (let ( (p (assoc key alist))) (if p (begin (set-cdr! p (list val)) alist ) (cons (list key val) alist) ) ) ) p points to: ((A 10) (B 20) (C 30)) before the set-struct! func is called: ______ |B | | ------ | \/ ------- |20| 0| -------- after call of set-struct!: ______ |B | | ------ | \/ ------- -------- |40 | 0| |20| 0| -------- --------- /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ in sheme binding of non-locals is static(lexical) --- binding is not done dynamically when they are called ex. (Define (F x) (lambda(y)(+ x y)) ) so..... (F 10) == (lambda(y)(+ 10 y)) (Define (P x) (+ x y)) -- when this is called it looks for a global binding to y, if there isn't one you get an error -- to bind: (Define y 30) another example of binding behavior: (Define I 20) (Define F (let ((I 1)) (x() I) ) ) call it: F --> 1 why? because I = 1 is closer than I = 20 another example of binding behavior: (Define CNT (let ((I 0)) (lambda()(set! I(+ I 1))I) ) ) -- this has a series of expressions and the last one is the one that returns a value running the func: (CNT) --> 1 (CNT) --> 2 --it only sets I = 0 the first time -- I is created and initialized only once when the func is defined -- to change it so that I is set every time revise as follows: (Define CNT2 (lambda () (let((I 0)) (set! I (+ I 1))I) ) ) ) /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class definitions in scheme (define (point x y) (list (list 'rect (lambda () (list x y))) (list 'polar (lambda () (list (sqrt (+ (* x x) (* y y))) (atan (/ x y))) )) )) -- point has 2 funcs -- rect and polar (Point 1 2) ((Rect Func1) (Polar Func2))