更好的方式嵌套if-let在clojure [英] Better way to nest if-let in clojure

查看:311
本文介绍了更好的方式嵌套if-let在clojure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张这张表格的地图:

 (def m {:aA:bB })

我想做一些事情,如果:a :b 都不是nil,我可以这样做:

 (if-let [a(:am)] 
(if-let [b(:bm)]
... etc))
/ pre>

  (:bm))
(let [{a:ab:b} m]
... etc))

或甚至

 (if(every?m [:a:b])
(let [{a:ab:b} m]
... etc))


$ b b

是否有更整洁的(即一行)方式来实现这一点?

解决方案

必要的在这里创建你想要的行为。我从来没有写过一个(但),但下面的代表建议我这可能是相当直接:

 (let [{ :key [ab]} m] 
(when(every?identity [ab])
(println(strProcessingaandb)))

使用:keys 形式的解构绑定和启用键向量的单一指定以进行重构和检查,并且绑定的局部变量在后面的代码块中可用。



这可以用来创建一个宏,例如(when-every?[keys coll] code-with-bindings)



我可以用宏代码来更新这个答案,如果我可以花时间了解如何做。


Say I have a map of this form:

(def m {:a "A" :b "B"})

and I want to do something if :a and :b are both not nil, I can do:

(if-let [a (:a m)]
  (if-let [b (:b m)]
      ... etc ))

or

(if (and (:a m) (:b m))
  (let [{a :a b :b} m]
      ... etc ))

or even

(if (every? m [:a :b])
  (let [{a :a b :b} m]
      ... etc ))

Is there a neater (ie one-line) way to achieve this?

解决方案

I think a macro may be necessary here to create the behavior you want. I have never written one (yet) but the following representation suggests to me that this might be fairly straightforward:

(let [{:keys [a b]} m]
   (when (every? identity [a b])
      (println (str "Processing " a " and " b))))

Using the :keys form of destructuring binding and every? enables a single specification of a vector of keys to destructure and check, and the bound locals are available in a following code block.

This could be used to make a macro such as (when-every? [keys coll] code-with-bindings)

I may update this answer with the macro code if I can take the time to work out how to do it.

这篇关于更好的方式嵌套if-let在clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆