Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Functions that churn out lambdas - when?

Name: Anonymous 2009-09-12 1:29

I just wrote my own "repeated" implementation (SICP lecture 3x), and I thought the same could have been done with something of the format (repeated procedure item times), instead of dealing with another layer of abstraction by churning out a procedure that does the actual iteration ((repeated procedure times) item). At this point, choosing between both forms seems like an arbitrary flip of the coin - can anyone on /prog/ enlighten me?

Name: Anonymous 2009-09-12 16:59

But to get back to OPs question:

When you have nested lambdas like that, you might ask yourself what the utility does and what is the most natural way of going about it, in accordance to the rest of your utilities and style you've adopted. So, for instance, given that (((repeated times) proc) item) repeats a (proc item) form 'times' times, I'd design it as:

(define (repeated proc item times)
  (if (> times 0)
    (begin
      (proc item)
      (repeated proc item (- times 1)))))


or in its more general form (to execute a block of forms N times), like this:


; this is common lisp because I don't know anything about scheme macros
(defmacro repeated (times &rest forms)
  `(progn
     ,@(make-list times :initial-element `(progn . ,forms))))


and if you're willing to go even more general, you'll write REPEATED like this:
(repeated (3 (form1) (form2)) (5 (form1) (form4)))


(defmacro repeated (&rest args)
  `(progn                
     ,@(mapcar (lambda (x)
                 `(progn
                    ,@(make-list (car x)                              
                                 :initial-element `(progn ,@(cdr x)))))
               args)))

Now you are able to execute arbitrary blocks of code arbitrary times in sequence, for instance:


(repeat (3 (princ 'X)) ; print X

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List