You can use the Clojure sequence to represent zero, one or more return values.
This is a smart approach and very idiomatic if your function is expected to return a collection.
However, I would not recommend using a sequence to emulate a parameter type. This is likely to confuse your API users. In Clojure, the normal and idiomatic way is to simply return nil if the value is not available, and return the value directly if there is one.
For comparison:
(if-let [a (function-that-returns-nil-or-result)] (do-something-with a))
What you will need if you used a sequence to emulate an option type:
(if-let [a (function-that-returns-a-possibly-empty-sequence)] (do-something-with (first a)))
I definitely prefer the first option .... why do we need or need the API user to unpack the result from the sequence using first
?
As a rule, nil works fine in Clojure (much better than in other languages), because:
- All library functions interpret nil as an empty sequence, so you are much less likely to work in NullPointerExceptions.
- nil is also considered "false", so it can be conveniently used in boolean operations.
source share