I'd like to propose the addition of the following function:
(defun maybecall (bool fn &rest args) "Call FN with ARGS if BOOL is T. Otherwise return ARGS as multiple values." (if bool (apply fn args) (values-list args)))
MAYBECALL is the general, or anonymous, solution to many ensure-foo problems.
(maybecall (not (listp thing)) #'list thing) == (ensure-list thing)
(maybecall (listp thing) #'car thing) == (ensure-car thing)
I've thought about naming it FUNCALL-IF, but that could be read as taking a predicate function a la all the sequence functions, rather than a boolean value. And the result of making it take a predicate
(funcall-if #'listp #'car thing)
is not so nice if you want the call not to depend directly on the arguments passed. E.g. a use case where I often use MAYBECALL is to call a function depending on a flag (most often argument to the surrounding function.)
I.e.
(maybecall removep #'remove foo bars)
vs.
(funcall-if (constantly removep) #'remove foo bars)
That said, I don't care much which of these two you eventually decide upon.
-T.
(maybecall (not (listp thing)) #'list thing) == (ensure-list thing)
i don't see in which aspect it is better than writing
(unless (listp thing) (list thing))
note that the rationale for ensure-list is that it's actually a bit shorter and also encodes the intention in a way that is much easier for a human to process (which, imho, can not be said for maybecall).
just my 0.02
"Attila Lendvai" attila.lendvai@gmail.com writes:
(maybecall (not (listp thing)) #'list thing) == (ensure-list thing)
i don't see in which aspect it is better than writing
(unless (listp thing) (list thing))
This would return NIL if THING is not a list. MAYBECALL behaves like a identity function in that case, making it practical for chaining.
note that the rationale for ensure-list is that it's actually a bit shorter and also encodes the intention in a way that is much easier for a human to process (which, imho, can not be said for maybecall).
I haven't said anything about taking ENSURE-LIST &c out. MAYBECALL behaves to ENSURE-FOO as LAMBDA behaves to DEFUN/FLET.
An advantage of FUNCALL-IF is also single evaluation of its arguments, so I actually opt for its inclusion.
-T.c
alexandria-devel@common-lisp.net