Crawler Tractor.








; This is so good that maybe I shouldn't write about it, but leave
; programmers to recognize this strange specie, function non-recursive,
; and without loop yet evaluating indefintely. However, some readers
; of this blog do not use Newlisp, so here is how it works:
;
; The function initially contains only one expression - starting
; with begin. That expression (i) prints some message; (ii) inserts
; its COPY after currently evaluated expression to body of the
; function, and (iii) deletes previously evaluated expression from
; the body of the function.

(set 'f (lambda()
            (begin (println "Hi for the " (inc counter) ". time. ")
                   (push (last f) f -1)
                   (if (> (length f) 3) (pop f 1)))))

(f)


; Hi for the 1. time.
; Hi for the 2. time.
; Hi for the 3. time.
; Hi for the 4. time.
; Hi for the 5. time.
; Hi for the 6. time.
; Hi for the 7. time.
; Hi for the 8. time.
; Hi for the 9. time.
; Hi for the 10. time.
; Hi for the 11. time.
; Hi for the 12. time.
; Hi for the 13. time.
; Hi for the 14. time.
; Hi for the 15. time.
; Hi for the 16. time.
; Hi for the 17. time.
; Hi for the 18. time.
; Hi for the 19. time.
; Hi for the 20. time.
; Hi for the 21. time.
;






3 comments:

  1. Just evaluated this 12996734 is like 30 seconds. Very interesting little piece of code. Thanks for sharing.

    ReplyDelete
  2. Very nice indeed!
    I made a "crawling" factorial function, just as a proof of concept.


    (define (f:f y)
      (begin
        (setq f:n 1)
        (setq f:current 0)
        (push
          '(if (> y 1)
             (begin
               (inc f:current)
               (setq f:n (* f:n y))
               (dec y)
               (if (and (> (length f:f) 3) (> f:current 2))
                 (pop f:f 2))
               (push (last f:f) f:f -1))
             f:n)
          f:f -1)))

    ReplyDelete
    Replies
    1. And another one, where the list to be pushed is modified instead of using variables.
      http://pastebin.com/HdQ8hiyx

      Delete

 
Real Time Web Analytics