Why don't when-let and if-let support multiple bindings by default?

前端 未结 3 524
悲&欢浪女
悲&欢浪女 2020-12-29 23:54

Why don\'t when-let and if-let support multiple bindings by default?

So:

(when-let [a ...
           b ...]
  (+ a b))
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 00:30

    Here is when-let*:

    (defmacro when-let*
      "Multiple binding version of when-let"
      [bindings & body]
      (if (seq bindings)
        `(when-let [~(first bindings) ~(second bindings)]
           (when-let* ~(vec (drop 2 bindings)) ~@body))
        `(do ~@body)))
    

    Usage:

    user=> (when-let* [a 1 b 2 c 3]
                    (println "yeah!")
                    a)
    ;;=>yeah!
    ;;=>1
    
    
    user=> (when-let* [a 1 b nil c 3]
                    (println "damn! b is nil")
                    a)
    ;;=>nil
    


    Here is if-let*:

    (defmacro if-let*
      "Multiple binding version of if-let"
      ([bindings then]
       `(if-let* ~bindings ~then nil))
      ([bindings then else]
       (if (seq bindings)
         `(if-let [~(first bindings) ~(second bindings)]
            (if-let* ~(vec (drop 2 bindings)) ~then ~else)
            ~else)
         then)))
    

    Usage:

    user=> (if-let* [a 1 
                     b 2 
                     c (+ a b)]
                  c
                  :some-val)
    ;;=> 3
    
    user=> (if-let* [a 1 b "Damn!" c nil]
                  a
                  :some-val)
    ;;=> :some-val
    

    EDIT: It turned out bindings should not be leaked in the else form.

提交回复
热议问题