【问题标题】:Clojure: Idiomatic/clean way to avoid NPE in a monad-like wayClojure:以类似单子的方式避免 NPE 的惯用/干净方式
【发布时间】:2015-06-15 16:33:54
【问题描述】:

有些内置 Clojure 函数的行为在我看来不一致,这让我有些懊恼。

我正在尝试这样做:

 (let [kwns (namespace (keyword v))]
   ...)

在 v 可能是 nil 的上下文中。 keyword 函数按我的预期工作(返回 nil),但命名空间抛出 NPE。

我的印象是,在 Clojure 中不经常使用 monad,因为 nil-punning 似乎是惯用的形式(正如 this article 所言长短)。

我预计 kwns 会出现 nil,而不是抛出 NPE。当这种不一致引起它丑陋的头脑时,保持代码清洁的推荐方法是什么......当然,nil 检查我的代码是不是我想要的答案。

【问题讨论】:

    标签: clojure


    【解决方案1】:

    some-> 适合你吗?

     user=> (doc some->)
     -------------------------
     clojure.core/some->
     ([expr & forms])
     Macro
       When expr is not nil, threads it into the first form (via ->),
       and when that result is not nil, through the next etc
     nil
     user=> (some-> nil keyword namespace)
     nil
     user=> (some-> "user/a" keyword namespace)
     "user"
    

    【讨论】:

    • 完美...我知道一定有什么!
    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2014-11-30
    • 2013-09-05
    • 2012-11-01
    相关资源
    最近更新 更多