【发布时间】:2015-09-21 22:02:56
【问题描述】:
我有一个函数需要根据提供的键调用稍微不同的逻辑。现在我正在使用这种丑陋的“嵌套如果”结构。有人可以告诉我一个更好、更清洁的方法吗?
(defn myfunc
"Do different things depending on which keys are given."
[{:keys [a b c]}]
;; If (myfunc {:a})
(if (not (nil? a))
(do-a)
;; If (myfunc {:b})
(if (not (nil? b))
(do-b)
;; If (myfunc {:c})
(if (not (nil? c))
(do-c)
;; If none of the above keys are available, do d
(do-d)))))
我可以使用(contains? ...),但是我不必在签名中指定密钥,它并没有真正改善嵌套结构。
理想情况下,我可以这样做:
(defn myfunc
"Do different things depending on which keys are given."
[{:keys [a b c]}]
(if (two-or-more-of [a b c])
(some-error)
(with
:a (do-a arg1)
:b (do-b arg2)
:c (do-c arg1 arg2)
else (do-d))))
注意:我的宏不够好,无法编写宏,但如果这是正确的答案并且有人想要,我会采用其他人的 =)
【问题讨论】:
标签: clojure