1

Is it possible to have keywords used\called conditionally? Essentially instead of:

(defun test (var) (if var (some-function :para var) (some-function))) 

I'd want something like this:

(defmacro test (var) `(some-function (if ,var [add-keyword]))) 

where the function is(for quick easy example purposes):

(defun some-function (&key para) (cond ((equal para 'yes) "yes") ((null para) "no") (t "other"))) 

2 Answers 2

3

It’s usually possible to write code in a way to not need to do this (just pass nil or the default). But if it really is unavoidable you can use apply:

(apply #'some-function args... (when var (list :para var))) 

If you want to pass keyword arguments on, you should use a &rest argument with apply and &allow-other-keys. If you want to pass them on to the next method in CLOS, you should use call-next-method. In general it is best to have the set of keyword arguments known at compile time because then the compiler can make things much faster than the unknown case.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Yeah I ended up rewriting the function(for other reasons), but the curiosity remained, haha.
3

One can also detect if a function was called with a keyword parameter:

CL-USER 44 > (flet ((example (&key (para nil para-supplied-p)) (list para para-supplied-p))) (list (example) (example :para nil) (example :para t))) ; para para-supplied-p ((NIL NIL) (NIL T) ( T T)) 

1 Comment

This doesn't allow for not passing a key value into the function though? The issue is I am working with SDL, and I wanted to not pass a color parameter if you didn't supply one, but SDL doesn't allow for a nil value on color, thereby forcing you to select a color(it probably defaults to main\screen color, so I rewrote it to mimic a related object's color). So while this would work if I developed the SDL library, I didn't thereby I needed my function to be able to select the passing of a key(pre-rewrite). Eitherway, thanks for your answer! I learned something new!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.