Reputation: 1722
In Clojure, the fnil function can be used to wrap another function: if the argument of the wrapped function would be nil
, the wrapper will change it to something else.
E.g. ((fnil * 0) nil) ; returns 0
However (* nil 0)
would throw an NPE.
What I'm asking is if there is a similar, built-in function that modifies the output, in case the input is nil
. (In other words, it does not even call the wrapped function, it just returns the default value instead.)
In other words, is there a built-in function equivalent to the following?
(defn ifnil [fun default]
(fn [& args]
(if (some nil? args) default (apply fun args))))
; ((ifnil * nil) 1 2 3) ; returns 6
; ((ifnil * nil) 1 nil 3) ; returns nil
N.B.: As always, "no, there is no such function" is also a valid answer (which I suspect, btw.)
Upvotes: 2
Views: 355
Reputation: 1681
There is no such a function, as far as I know. Your implementation looks well, so why not to use it in your code.
What may be improved here is a better name of the function: ifnil
might be a bit confusing for your teammates or those who will support your code.
Also, you said in case the input is nil
. But in your code, you check for at least one argument is nil
. That differs slightly.
And one more thing, personally I'm not a fan of failing to defaults silently. Maybe, you'd better to validate the input data either manually or using schema/spec and write logs. Because fnil
mostly used for non-existing keys with update
/update-in
. But you function tends to be rather a validator.
Upvotes: 1