In Clojure/conj talks Effective Programs and Maybe Not, Rich Hickey pointed that if we don't know something we should leave it out, i.e. we should not have keyword-nil (spec/nilable) pairs in maps.
如何处理这种情况的最佳方法
(defn person
[line]
{:person/name (name line) ;; req
:person/height (height line)}) ;; opt, height may return nil
我想出了以下解决方案
为'opt'函数添加附加的arity:keyword和map,以便它们可以条件性地assoc。通过threading宏将一切组合起来。只有如果你"拥有"这些函数时才适用。
(defn person
[line]
(->> {:person/name (name line)}
(height line :person/height)))
在调用位置进行检查并使用some.我认为这真的很丑,想象一下多个可选的-if-lets该如何避免嵌套?
(defn person
[line]
(let [ret {:person/name (name line)}]
(if-let [height (height line)]
(assoc ret :person/height height)
ret)))