[pro] Style issue about predicates

Tobias C Rittweiler tcr at freebits.de
Sun Jan 16 10:41:39 UTC 2011


In article <4D307CE8.1000208 at itasoftware.com>,
 Daniel Weinreb <dlw at itasoftware.com> wrote:

> If you have a function that is a predicate, in the sense that
> the function's contract says that its value should be interpreted
> as being either false or true, do you think it's better to code
> it so that it always returns "t" for the true case?
> 
> Since Common Lisp is quite clear that when a value
> is being considered in the context of being true/false,
> nil means false and everything else means true.
> So from a language point of view, even considering
> the "intent" of the definition and not just the spec,
> there is no need to return t.
> 
> Furthermore, the contract of the function should
> make it clear that the returned value is an a
> true/false context.  This should be in the doc
> string, or at least in a comment, and the function
> name should end in "p" (or always "-p" but let's
> please not get into that in this email thread).
> So the caller should know.
> 
> All that said, it's possible that a programmer will
> fail to heed the contract, simply look at the code,
> and take advantage of the returned value in
> more than true/false context.  If you want to prevent
> that, you can do something like:
> 
> (defun ...
> ...
> (when (fn1 arg2 arg2)
>   t))
> 
> It seems that it might depend on the circumstance: how likely
> do you think it is that a programmer would commit such
> a mistake?  The more potentially valuable the returned value
> is, the more likely.  On the other hand, if it's so valuable,
> maybe you should actually make that part of the contract
> rather than making the function have the contract of
> a predicate.
> 
> Is this good, bad, don't care, depends on the circumstance?
> 
> -- Dan


I think it's good style to make predicates return T (except
for the rare case Edi cited where the return value could
also legitimately be made sense of differently.)

Returning another value that the user might see
when playing at the REPL seems like leaking internal
decomposition to me.

I also prefer to use (AND (FOO ...) T) rather than
WHEN in that case because WHEN is a control-flow
construct but this case is about data normalization,
and thus I consider AND more appropriate.

   -T.





More information about the pro mailing list