; Expression evals - Can you compose these relations?
; ------------------------------
; The Little Lisper 3rd Edition
; Chapter 8
; Exercise 8
; 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 member* (a l)
(cond
((null l) NIL)
((atom (car l))
(or
(eq (car l) a)
(member* a (cdr l))))
(t (or
(member* a (car l))
(member* a (cdr l))))))
(defun eqlist? (l1 l2)
(cond
((and (null l1) (null l2)) t)
((or (null l1) (null l2)) NIL)
(t (and
(eq (car l1) (car l2))
(eqlist? (cdr l1) (cdr l2))))))
(defun member_ (lista listb)
(cond
((null lista) t)
((null listb) NIL)
((atom listb)
(eq lista listb))
((atom lista)
(member* lista listb))
((eqlist? lista listb) t)
(t (or (member_ lista (car listb))
(member_ lista (cdr listb))))))
;(t NIL)))
(defun union_ (set1 set2)
; (print 'union_)
; (print set1)
; (print set2)
(cond
((null set1) set2)
((member_ (car set1) set2) ;member?
(union_ (cdr set1) set2)) ; union_
(t (cons (car set1)
(union_ (cdr set1) set2))))) ;union_
(union_ '(tomatoes and marcaroni casserole) '(marcaroni and cheese))
;(TOMATOES CASSEROLE MARCARONI AND CHEESE)
(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)))
(defun lat? (l)
(cond
((null l) t)
((atom (car l)) (lat? (cdr l)))
(t nil)))
(defun build (a b)
(cons a (cons b '())))
(defun rin (x set)
(cond
((null x) NIL)
((null set) '())
((lat? set)
(cons (build x (car set))
(rin x (cdr set))))
(t NIL)))
(defun rcomp (rel1 rel2)
; (print 'rcomp)
; (print rel1)
; (print rel2)
(cond
((null rel1) '())
(t (union_ ;'union_
(rin
(first_ (car rel1))
(rapply rel2 (second_ (car rel1))))
(rcomp (cdr rel1) rel2)))))
(print (rcomp '((a b)(b d)) '((a b)(b d))))
;((a d))
(print (rcomp '((a b)(b d)) '((a b)(b d))))
;((a d))
(print (rcomp r1 r3))
;((A C) (A C) (B C))
(print (rcomp r1 f1))
;((A 2) (A 1) (B 2))
(print (rcomp r1 r1))
;((A B) (A A) (B B))