[pro] Style issue about predicates

Edi Weitz edi at weitz.de
Fri Jan 14 16:59:52 UTC 2011


There are lots of functions in the standard which are predicates in
that they return generalized booleans but on the other hand return
something "useful" if the result is not NIL, e.g. MEMBER or STRING<.
I think this is good practice, i.e. return something other than T in
case this might make more sense.  Of course, this should then be
documented in the predicate's contract and thus should be OK to use by
the caller.

On Fri, Jan 14, 2011 at 5:42 PM, 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
>
>
> _______________________________________________
> pro mailing list
> pro at common-lisp.net
> http://common-lisp.net/cgi-bin/mailman/listinfo/pro
>
>




More information about the pro mailing list