Welcome! Please see the About page for a little more info on how this works.

+3 votes
in Macros by

I feel like with pair of macros if and cond we miss companion macro for if-let:

(defmacro cond-let
  [& clauses]
  (when clauses
    (if (next clauses)
      (list 'if-let (first clauses)
            (second clauses)
            (cons 'cond-let (nnext clauses)))
      (first clauses))))

(cond-let [a nil] {:a a}
          [b false] {:b b}
          :default)

I did not find if this variation of cond-let (without introducing much new syntax) macro were discussed in the past but generally it looks like natural for clolure.core.

2 Answers

0 votes
by

When would you use it?

by
I worked with code having multiple nested `if-let` and found this pattern.
```
(if-let [a ...]
  (do a)
  (if-let [b ...]
    (do b)
    (do :default))
```
Later I realized that this rare situation and such macro is not very useful.
Sorry for disturbance.
Let's forget about this incident :-)
by
edited by
I do sometimes "need" something like this. Very concrete example:

```
(cond-let
  [search-results1 (check1-involving-heavy-work)] {:result search-results1}
  [search-results2 (check2-involving-heavy-work)] {:result search-results2}
  [search-results3 (check3-involving-heavy-work)] {:result search-results3}
  [search-results4 (check4-involving-heavy-work)] {:result search-results4}
  :else ...)
```

I found this: https://cljdoc.org/d/org.flatland/useful/0.11.6/api/flatland.useful.experimental#cond-let

Not sure why it is "experimental", but this seems to be, well, useful to me :)

(* updated to make example a bit more clear; it's a hypothetical example, don't pin me down on the details and how you could do this exact example differently please :) *)
0 votes
by

+1 for this.

This is when you want the conditional expression to return a useful value instead of true/false and use that value in the body as is.
If there are multiple conditions, the if-let is nested, but being able to describe it flatly is considered to contribute to readability.

...