; Expression evalutors - Can you evaluate this relation?
; ------------------------------
; The Little Lisper 3rd Edition
; Chapter 8
; Exercise 6
; 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 rapply (rel x)
(cond
((null rel) '())
((null x) NIL)
((and (rel? rel) (atom x))
(cond
((eq (first_ (car rel)) x)
(cons (second_ (car rel)) (rapply (cdr rel) x)))
(t (rapply (cdr rel) x))))
(t NIL)))
(print (rapply '((a 1)(b 2)) 'b))
;(2)
(print (rapply f1 x))
;(1)
(print (rapply r1 x))
;(b a)
(print (rapply f2 x))
;NIL