fork download
  1. ; Expression evalutors - What is value of f at x?
  2. ; ------------------------------
  3. ; The Little Lisper 3rd Edition
  4. ; Chapter 8
  5. ; Exercise 4
  6. ; Common Lisp
  7. ; http://t...content-available-to-author-only...r.com/thelittlelisper
  8. ; http://t...content-available-to-author-only...t.com/2010/06/little-lisper-chapter-8-friends-and.html
  9. ; http://t...content-available-to-author-only...t.com/2010/06/little-lisper.html
  10. ; ------------------------------
  11. (setf r1 '((a b)(a a)(b b)))
  12. (setf r2 '((c c)))
  13. (setf r3 '((a c)(b c)))
  14. (setf r4 '((a b)(b a)))
  15. (setf f1 '((a 1)(b 2)(c 2)(d 1)))
  16. (setf f2 '())
  17. (setf f3 '((a 2)(b 1)))
  18. (setf f4 '((1 $)(3 *)))
  19. (setf d1 '(a b))
  20. (setf d2 '(c d))
  21. (setf x 'a)
  22. ; ------------------------------
  23.  
  24. (defun first_ (l)
  25. (cond
  26. ((null l) '())
  27. (t (car l))))
  28.  
  29. (defun second_ (l)
  30. (cond
  31. ((null l) '())
  32. (t (car (cdr l)))))
  33.  
  34. (defun third_ (l)
  35. (cond
  36. ((null l) '())
  37. (t (car (cdr (cdr l))))))
  38.  
  39. (defun pair? (lat)
  40. (cond
  41. ((null lat) NIL)
  42. ((atom lat) NIL)
  43. ((and (and (not (eq (first_ lat) NIL))
  44. (not (eq (second_ lat) NIL))))
  45. (eq (third_ lat) NIL))
  46. (t NIL)))
  47.  
  48. (defun rel? (rel)
  49. (cond
  50. ((null rel) t)
  51. ((atom rel) NIL)
  52. ((pair? (car rel))
  53. (rel? (cdr rel)))
  54. (t NIL)))
  55.  
  56. (defun fapply (f x)
  57. (cond
  58. ((null f) NIL)
  59. ((null x) NIL)
  60. ((and (rel? f) (atom x))
  61. (cond
  62. ((eq (first (car f)) x) (second (car f)))
  63. (t (fapply (cdr f) x))))
  64. (t NIL)))
  65.  
  66. (print (fapply '((a 1)(b 2)) 'b))
  67. ;2
  68.  
  69. (print (fapply f1 'x))
  70. ;book incorrect - presume they mean 'a - merely a typo
  71. ;NIL no answer
  72.  
  73. (print (fapply f2 'x))
  74. ;NIL no answer
  75.  
  76. (print (fapply f3 'x))
  77. ;NIL no answer
  78.  
  79. (print (fapply f1 'a))
  80. ;1
  81.  
  82. (print (fapply f2 'a))
  83. ;NIL no answer
  84.  
  85. (print (fapply f3 'a))
  86. ;2
  87.  
Success #stdin #stdout 0s 10600KB
stdin
Standard input is empty
stdout
2 
NIL 
NIL 
NIL 
1 
NIL 
2