; Expression evalutors - What is value of f at x?
; ------------------------------
; The Little Lisper 3rd Edition
; Chapter 8
; Exercise 4
; Common Lisp
; http://t...content-available-to-author-only...r.com/thelittlelisper
; http://t...content-available-to-author-only...t.com/2010/06/little-lisper-chapter-8-friends-and.html
; http://t...content-available-to-author-only...t.com/2010/06/little-lisper.html
; ------------------------------
(setf r1 '((a b)(a a)(b b)))
(setf r2 '((c c)))
(setf r3 '((a c)(b c)))
(setf r4 '((a b)(b a)))
(setf f1 '((a 1)(b 2)(c 2)(d 1)))
(setf f2 '())
(setf f3 '((a 2)(b 1)))
(setf f4 '((1 $)(3 *)))
(setf d1 '(a b))
(setf d2 '(c d))
(setf x 'a)
; ------------------------------
(defun first_ (l)
(cond
((null l) '())
(t (car l))))
(defun second_ (l)
(cond
((null l) '())
(t (car (cdr l)))))
(defun third_ (l)
(cond
((null l) '())
(t (car (cdr (cdr l))))))
(defun pair? (lat)
(cond
((null lat) NIL)
((atom lat) NIL)
((and (and (not (eq (first_ lat) NIL))
(not (eq (second_ lat) NIL))))
(eq (third_ lat) NIL))
(t NIL)))
(defun rel? (rel)
(cond
((null rel) t)
((atom rel) NIL)
((pair? (car rel))
(rel? (cdr rel)))
(t NIL)))
(defun fapply (f x)
(cond
((null f) NIL)
((null x) NIL)
((and (rel? f) (atom x))
(cond
((eq (first (car f)) x) (second (car f)))
(t (fapply (cdr f) x))))
(t NIL)))
(print (fapply '((a 1)(b 2)) 'b))
;2
(print (fapply f1 'x))
;book incorrect - presume they mean 'a - merely a typo
;NIL no answer
(print (fapply f2 'x))
;NIL no answer
(print (fapply f3 'x))
;NIL no answer
(print (fapply f1 'a))
;1
(print (fapply f2 'a))
;NIL no answer
(print (fapply f3 'a))
;2
OyBFeHByZXNzaW9uIGV2YWx1dG9ycyAtIFdoYXQgaXMgdmFsdWUgb2YgZiBhdCB4Pwo7IC0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLQo7IFRoZSBMaXR0bGUgTGlzcGVyIDNy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