siltalau
siltalau

Reputation: 549

Clojure optional argument to function call

I have a value athat may or may not be nil.

I have a bunch of functions (outside my control) that should be called with the value of a as the first parameter if it is not nil. If it is nil, the function should be called without a.

Instead of:

(defn my-fn [x]
  (if a
      (beyond-my-control-fn a x)
      (beyond-my-control-fn x)))

I'd like to do something like:

(defn my-fn [x]
  (add-argument-if-not-nil-> a (beyond-my-control-fn x)))

Is there a macro that allows me to do this already or should I make my own?

Upvotes: 2

Views: 2210

Answers (2)

mavbozo
mavbozo

Reputation: 1261

You can wrap the calling of those beyond-your-control functions with another function

(defn call-with-a-if-not-nil
  [f a & args]
  (if (nil? a)
    (apply f args)
    (apply f a args)))

samples:

(call-with-a-if-not-nil beyond-my-control-fn a x)

(call-with-a-if-not-nil beyond-my-control-fn-1 a v w)

Upvotes: 5

siltalau
siltalau

Reputation: 549

mavbozo's answer is correct. I went with a macro due to a personal dislike of simple functions as parameters.

(defmacro nn-> [x form]
  (if x
    `(-> ~x ~form)
    `~form))

This allows me to use it like so:

(nn-> a (beyond-my-control-fn x))

(nn-> a (beyond-my-control-fn x y z))

which is, to me, more elegant.

Upvotes: 2

Related Questions