为什么默认情况下when-let和if-let不支持多个绑定?

pon*_*zao 22 clojure

为什么不when-letif-let默认支持多个绑定?

所以:

(when-let [a ...
           b ...]
  (+ a b))
Run Code Online (Sandbox Code Playgroud)

...代替:

(when-let [a ...
  (when-let [b ...
    (+ a b)))
Run Code Online (Sandbox Code Playgroud)

我知道我可以编写自己的宏或使用monad(如此处所述:http://inclojurewetrust.blogspot.com/2010/12/when-let-maybe.html).

and*_*oke 14

因为(if-let至少)对于"其他"案件不明白该怎么做.

至少,由于更好的方式来嵌套if-let in clojure,我开始编写一个宏来做这件事.特定

(if-let* [a ...
          b ...]
  action
  other)
Run Code Online (Sandbox Code Playgroud)

它会产生

(if-let [a ...]
  (if-let [b ...]
    action
    ?))
Run Code Online (Sandbox Code Playgroud)

我不清楚如何继续("其他"有两个地方).

您可以说任何失败应该有一个替代方案,或者没有任何失败,when-let但如果任何测试变异状态,那么事情仍然会变得混乱.

简而言之,它比我预期的要复杂一点,所以我猜当前的方法避免了必须调用解决方案应该是什么.

另一种说同样的方式:你假设if-let应该像窝一样let.一个更好的模型可能是cond,这不是"嵌套if",而是更多"替代if",因此不适合范围......或者,另一种说法:if不处理这种情况好点.


Ert*_*tin 7

这是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)))
Run Code Online (Sandbox Code Playgroud)

用法:

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
Run Code Online (Sandbox Code Playgroud)


这是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)))
Run Code Online (Sandbox Code Playgroud)

用法:

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
Run Code Online (Sandbox Code Playgroud)

编辑:事实证明,绑定不应该以其他形式泄露.


nha*_*nha 5

如果您使用cats,那么mlet您可能会发现一个有用的功能:

(use 'cats.builtin)
(require '[cats.core :as m])
(require '[cats.monad.maybe :as maybe])

(m/mlet [x (maybe/just 42)
         y nil]
  (m/return (+ x y)))
;; => nil
Run Code Online (Sandbox Code Playgroud)

如您所见,当遇到零值时,mlet会短路.

(来自6.5.1节)