; Expression evaluators - Compose function f and g?
; ------------------------------
; The Little Lisper 3rd Edition
; Chapter 8
; Exercise 5
; 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)))
(defun fcomp-pair (rel1 pair)
(cond
((null rel1) '())
((null pair) NIL)
((and (rel? rel1) (pair? pair))
(cond
((not (null (fapply rel1 (second pair))))
(build (first pair) (fapply rel1 (second pair))))
(t NIL)))
(t NIL)))
(fcomp-pair '((a b)(c d)) '(a c))
;(a d)
(fcomp-pair '((a b)(c d)) '(a b))
;NIL
(defun fcomp (rel1 rel2)
(cond
((null rel1) '())
((null rel2) NIL)
((and (rel? rel1) (rel? rel2))
(cond
((not (null (fapply rel1 (second (car rel2)) )))
(cons (fcomp-pair rel1 (car rel2))
(fcomp rel1 (cdr rel2))))
(t (fcomp rel1 (cdr rel2)))))
(t NIL)))
(print (second (car '((b c)(d e)))))
;C
(print (fapply '((a b)(c d)) 'c))
;D
(print (fapply '((a b)(c d)) (second (car '((b c)(d e))))))
;D
(print (fcomp '((y z)) '((x y))))
; ((X Z))
(print (fcomp '((b c)(d e)) '((a b)(c d))))
;((A C) (C E))
(print (fcomp f1 f4))
;NIL
(print (fcomp f1 f3))
;NIL
(print (fcomp f4 f1))
;((A $) (D $))
(print (fcomp f4 f3))
;((B $))