Useful function proposal: doif

Started by Dmi, June 15, 2007, 04:28:13 AM

Previous topic - Next topic

Dmi

doif macro:
Quotesyntax: (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 ().

(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:
(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
(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:
(doif (l (function-can-return-nil))
  do-something-if-found
  do-something-if-not))

Or for real example:
(define (xml-data tag xml)
  (doif (r (assoc 0 (map reverse (ref-all tag xml))))
        (xml (chop (reverse r)))))
WBR, Dmi

rickyboy

#1
By the way, Dmi, your doif is called an http://community.schemewiki.org/?anaphoric-if">anaphoric if, in programming language parlance.



Here's Paul Graham on the subject (from On Lisp, Chapter 14):


Quote from: "Paul Graham"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
(λx. x x) (λx. x x)