This would be a straightforward solution:

(defmacro when-lets [bindings & body]
  `(let ~bindings
     (when (and ~@(map first (partition 2 2 bindings)))
       ~@body)))

It works well in simple cases, but breaks e.g. in case of parameter
destructuring.
If you read `(source when-let)`, you'll see that it uses a temporary
binding. So we can add that and a loop, or just reuse `when-let` and
use something akin to recursion:

(defmacro when-lets [bindings & body]
  (if (empty? bindings)
    `(do ~@body)
    `(when-let [~@(take 2 bindings)]
       (when-lets [~@(drop 2 bindings)]
          ~@body))))

user=> (when-lets [a 1 [b c] [1 2]] (+ a b c))
4
user=> (when-lets [a 1 [b c] nil] (+ a b c))
nil

Questions?

On Jul 27, 4:50 pm, Feng Shen <shen...@gmail.com> wrote:
> Clojure core.clj has a macro when-let,
> I am wondering how to write a macro `when-lets`
>
> (when-lets [symbol-1 test-1
>                    symbol-2 test-2
>             ...
>             ]
>            body
>            )
>
> body only get evaluated when (and test-1 test-2 ....)
> I am thinking about it, anybody has any clue?

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to