Page 1 of 1

IF/WHEN?

PostPosted: Thu Nov 06, 2008 8:10 am
by humpolec
I often run into cases where I want to write "if A then B else NIL" (that is, the result matters either way.)
Should I use (IF A B NIL), (IF A B), or (WHEN A B)? What is the convention?

Re: IF/WHEN?

PostPosted: Thu Nov 06, 2008 9:12 am
by stefano
When the result matters (i.e. the value nil has a specific meaning) I prefer to use (if A B nil).

Re: IF/WHEN?

PostPosted: Thu Nov 06, 2008 10:23 am
by danb
If you're only using B as a boolean, you should write (and a b).

Re: IF/WHEN?

PostPosted: Thu Nov 06, 2008 10:31 am
by findinglisp
If the result matters, I would probably use IF to make that clear. But if it doesn't (and even sometimes when it does), I use WHEN. The semantics of WHEN in this case are clearly defined, so it isn't like you'd be straying into vague areas of the CLHS, but it's simply less visible. If you're writing for the code reader, use IF.

Re: IF/WHEN?

PostPosted: Thu Nov 06, 2008 9:21 pm
by JamesF
humpolec wrote:Should I use (IF A B NIL), (IF A B), or (WHEN A B)? What is the convention?

I'm not 100% sure of the convention, but I tend to use IF where I'm providing a clause for both the true and false cases, and WHEN/UNLESS if the second clause would be NIL anyway.
Sometimes it clarifies my intentions (only do B if A is the case), but mostly it saves me looking for the alternative return clause in an IF statement: WHEN makes it explicitly clear that there isn't one.

I think this shares its motivation with my liking for the parentheses: lisp is great for avoiding ambiguity in my code.

Re: IF/WHEN?

PostPosted: Sat Nov 08, 2008 1:12 pm
by donkey
I'm not sure what's the "official" (i.e. accepted) convention for this, but I usually prefer IF in this case. Although would work just as well, I prefer to keep when for performing side-works that are necessary only in some cases. IF tends to make it clear that what the clause is returning really is a meaningful result that will be used later.

Re: IF/WHEN?

PostPosted: Sat Dec 27, 2008 3:17 pm
by OohLunchCzar
I am among those who use IF for the reader's benefit though I will occasionally use WHEN in the event that it does not detract from understanding.