I've been trying to find info on this online, but haven't been successful so far. I've been finding myself needing to construct data with optional contents based on some conditions. For example, if config.verbose is true, add the pair [(constantly true) "result"] to the list. However, I'm struggling to express this concisely. One way would be creating the full list and then filtering nils, like so (all the get-value functions returning nil if the value is not set):
(let [result [(get-value-for-config-option-a config) (get-value-for-config-option-b config)]]
(filterv some? result))
Is there a nicer way to express this?I find that cond-> can help a lot in those cases. But I do find myself putting nils and filtering the result when cond-> gets too verbose
Thanks for the pointer!
(cond-> []
verbose? (conj :verbose)
some-opt (conj 1)
...)
or concat in your example. Works well with map + assoc tooRight, this is nice, that is exactly what I was looking for!
Edit: I stumbled on something similar with a reduce and a sequence of functions, but that was quite complicated, I thought.
On Clojuredocs, the cond->> page has a nice example of the above idiom where you get those test clauses from destructuring a map https://clojuredocs.org/clojure.core/cond-%3E%3E#example-555ce83ee4b01ad59b65f4d2
here's one way to do it, if I understand the question correctly
(ins)user=> (reduce into []
[(if nil [:a])
(if true [:b])
(if false [:c])
[:d]])
[:b :d]
cond->> is probably nicer if you know all the conditions at compile time
I don't like about this that all the tests have to return a list.