fork download
  1. ; Can you combine an S-expr and a thunk to make a stream?
  2. ; ------------------------------
  3. ; The Little Lisper 3rd Edition
  4. ; Chapter 9
  5. ; Exercise 9
  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-9-lamdba-ultimate.html
  9. ; http://t...content-available-to-author-only...t.com/2010/06/little-lisper.html
  10. ; ------------------------------
  11.  
  12. (defun add1 ()
  13. (lambda (n)
  14. (+ 1 n)))
  15.  
  16. (setf zero 0)
  17.  
  18. (defun zero (n)
  19. (cond
  20. ((null n) '())
  21. ((= zero n) t)
  22. (t '())))
  23.  
  24. (defun sub1 (n)
  25. (cond
  26. ((null n) '())
  27. ((- n 1))))
  28.  
  29.  
  30. (print (funcall (add1) 1))
  31. ;2
  32.  
  33. (defun build (a b)
  34. (cons a (cons b '())))
  35.  
  36. (defun str-maker (next n)
  37. (build n (lambda () (str-maker next (funcall (funcall next) n)))))
  38.  
  39. (defun int_ () (str-maker 'add1 0))
  40.  
  41. (defun add2 ()
  42. (lambda (n)
  43. (+ 2 n)))
  44.  
  45. (print (funcall (add2) 1))
  46. ;3
  47.  
  48. (defun even () (str-maker 'add2 0))
  49.  
  50. (defun odd () (str-maker 'add2 1))
  51.  
  52. (defun frontier (str n)
  53. (cond
  54. ((zero n) '())
  55. (t (cons (first (funcall str)) (frontier (second (funcall str)) (sub1 n))))))
  56.  
  57. (print (frontier #'int_ 10))
  58. ;(0 1 2 3 4 5 6 7 8 9)
  59.  
  60. (print (frontier #'int_ 100))
  61. ;(0 1 2 3 4 5 6 7 8 9 ...)
  62.  
  63. (print (frontier #'even 23))
  64. ;(0 2 4 6 8 10 12 14 16 18 ...)
  65.  
  66. (print (frontier (function odd) 10))
  67. ;(1 3 5 7 9 11 13 15 17 19)
  68.  
Success #stdin #stdout 0.01s 10784KB
stdin
Standard input is empty
stdout
2 
3 
(0 1 2 3 4 5 6 7 8 9) 
(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
 99) 
(0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44) 
(1 3 5 7 9 11 13 15 17 19)