Page 1 of 1

Useful function proposal: doif

Posted: Fri Jun 15, 2007 11:28 am
by Dmi
doif macro:
syntax: (doif (sym expr) expr-yes expr-no))

expr is evaluated and assigned to sym
If then sym is not nil or (), then expr-yes is evaluated while sym is defined and can be used.
Otherwise expr-no is evaluated sym is still defined and can be used to distinguish between nil or ().

Code: Select all

(context 'doif)
(define-macro (doif:doif test do-yes do-no)
              (eval
                (list let test (list 'if (first test) do-yes do-no))))
(context MAIN)
Frequently I using something like this:

Code: Select all

(let (l (function-can-return-nil))
  (if l do-something-if-found
        do-something-if-not))
From the point of task logic this usually looks cryptic.
Real world example:
Find a tag or an attribute in xml s-expression

Code: Select all

(define (xml-data tag xml)
  (let (r (assoc 0 (map reverse (ref-all tag xml))))
        (if r (xml (chop (reverse r))))))
I would like to propose the new form to write this:

Code: Select all

(doif (l (function-can-return-nil))
  do-something-if-found
  do-something-if-not))
Or for real example:

Code: Select all

(define (xml-data tag xml)
  (doif (r (assoc 0 (map reverse (ref-all tag xml))))
        (xml (chop (reverse r)))))

Posted: Fri Jun 15, 2007 12:40 pm
by rickyboy
By the way, Dmi, your doif is called an anaphoric if, in programming language parlance.

Here's Paul Graham on the subject (from On Lisp, Chapter 14):
Paul Graham wrote:In natural language, an anaphor is an expression which refers back in the conversation. The most common anaphor in English is probably "it," as in "Get the wrench and put it on the table." Anaphora are a great convenience in everyday language--imagine trying to get along without them--but they don't appear much in programming languages. For the most part, this is good. Anaphoric expressions are often genuinely ambiguous, and present-day programming languages are not designed to handle ambiguity.

However, it is possible to introduce a very limited form of anaphora into Lisp programs without causing ambiguity. An anaphor, it turns out, is a lot like a captured symbol. We can use anaphora in programs by designating certain symbols to serve as pronouns, and then writing macros intentionally to capture these symbols.
Cheers, --Rick