| I'm very fond of conanite's "afnwith" macro (http://arclanguage.org/item?id=10055). It encapsulates the common pattern of a loop where I start with some initial variable values, and then each time through the loop I give the variables new values. For example, using "afn": (def span (tst lst)
; "a" and "lst" are the loop variables
((afn (a lst)
(if (and lst (tst (car lst)))
; do another pass through the loop with new
; values for "a" and "lst"
(self (cons (car lst) a) (cdr lst))
(list (rev a) lst)))
; initial values for "a" and "lst"
nil lst))
with conanite's afnwith, I can write this as: (def span (tst lst)
; the loop variables "a" and "lst" and
; their initial values
(afnwith (a nil lst lst)
(if (and lst (tst (car lst)))
(self (cons (car lst) a) (cdr lst))
(list (rev a) lst))))
This has two nice features: the initial values for the variables are up at the top next to the variables instead of lost at the bottom, and I don't have the double parentheses needed by "afn".In terms of naming, the name of Arc's "afn" ("anaphoric function") makes sense, since it returns a function. However, "afnwith", while it encapsulates a way I commonly use "afn" and it looks like a "with", doesn't return a function and so couldn't be used in cases where I needed a function instead of doing a loop. Hmm, so how about calling it "loop"? And perhaps "next" for making another iteration through the loop. With these renames, and using "rfn" so that "next" can be used, conanite's macro now looks like: (mac loop (withses . body)
(let w (pair withses)
`((rfn next ,(map car w) ,@body) ,@(map cadr w))))
and "span" can be written like this: (def span (tst lst)
(loop (a nil lst lst)
(if (and lst (tst (car lst)))
(next (cons (car lst) a) (cdr lst))
(list (rev a) lst))))
Of course, Arc already has a "loop" macro. However, I've never used it, and it's only used once in news. And even in news, where it's used in "each-loaded-item", that looks like it could be more simply written with "down" anyway. So Arc's "loop" macro, which is used in arc.arc in the definitions of "for" and "down", could be renamed to something more boring. |