when-macro


The IF form allows only one expression in the consequent clause, which can be annoying at times. Therefore, some people like to introduce a WHEN form:

 (define-syntax when 
   (syntax-rules () 
     ((when condition body ...) 
      (if condition 
          (begin body ...))))) 

The following are all equivalent:

 (if test? 
     (begin 
       (foo) 
       (bar) 
       (baz))) 
  
 (cond  
   (test?  (foo) 
           (bar) 
           (baz))) 
  
 (when test? 
   (foo) 
   (bar) 
   (baz)) 

WHEN stems from earlier Lisps that allowed any number of forms in the alternative clause of an IF, but only one in the consequent clause. Emacs Lisp? is especially well-known for using WHEN very often. It isn't seen as often in Scheme since Scheme encourages a functional programming style where you have fewer side-effectual idioms that would mandate using a sequence of commands. For those few times this is needed, IF/BEGIN and COND are used most of the time.

Another reason why this idiom is less useful in Scheme is that, in Emacs Lisp for example, WHEN returns nil (#F) if the test argument is false - in the Scheme definition above, you can't rely on the return value (it is "undefined" for the false case).

pitecus

This argument doesn't make sense to me, as WHEN isn't normally used for it's return value, but rather to conditionally execute side effecting code, so the undefined return value in the false case is a feature, not a bug.


Jorgen-Schäfer

In elisp, side-effect stuff is often used, and (when foo bar) is often used as a shorthand for (if foo bar nil)....


Unknown-Author

Uh, so why bother with WHEN at all? Perhaps to make it more explicit that side effecting code is used. Similar to using "!" in side effecting procedure names?


Jorgen-Schäfer

People use WHEN because they come from an emacs/common lisp background, or they enjoy it's conciseness...


Edwin-Zacharias

I use WHEN and UNLESS because they are more descriptive. You can use OR instead of UNLESS the same way you can use IF instead of WHEN, but I find it really confusing when I see OR used as a conditional.


Jorgen-Schäfer

I do agree completely here. OR as a conditional does not make sense often (actually, it only makes sense if you want to return either this or that value...). WHEN and IF are equal in expressive power, WHEN can be slightly more concise. UNLESS is abused. You should use UNLESS when it's the natural thing to say. Not every (if (not ...) ...) is a useful candidate for UNLESS, and actually, almost none of them is.



category-code