我有一个小的 clojure 功能:
(defn split-legal-ref
"Highly specific function that expects one AssessPro map and a map key,
from which book and page will be extracted."
[assess-pro-acct extract-key]
(let [[book page] (cstr/split (extract-key assess-pro-acct) #"-")]
(list (cstr/trim book) (cstr/trim page))))
Run Code Online (Sandbox Code Playgroud)
鉴于此:(extract-key assess-pro-acct) #"-")
,extract-key
的值为:legal_ref
。因此,它927-48
从地图中获取单个值并使用“-”拆分该值。当没有这些好的值之一时,我只需要抓住。这就是 split 返回 nil 的地方。
因此,我试图用以下内容替换原始功能时陷入困境。
(def missing-book 888)
(def missing-page 999)
.
.
.
(defn split-legal-ref
"Highly specific function that expects one AssessPro map and a map key,
from which book and page will be extracted."
[assess-pro-acct extract-key]
(let [[book page] (cstr/split (extract-key assess-pro-acct) #"-")]
(let [[trimBook trimPage] ((if book (cstr/trim book) (missing-book))
(if page (cstr/trim page) (missing-page)))]
(list (trimBook) (trimPage)))))
Run Code Online (Sandbox Code Playgroud)
问题是我一直在害怕
String cannot be cast to clojure.lang.IFn From Small Clojure Function
错误。如何重构此函数以避免错误?
发布答案编辑:
感谢您的回答:
我重新编写了函数以测试字符串中的“-”。如果它不存在,我会使用一个虚拟的“888-99”作为一个值,当没有的时候。
(def missing-book-page "888-99")
.
.
.
(defn split-legal-ref
"Highly specific function that expects one AssessPro map and a map key,
from which book and page will be extracted."
[assess-pro-acct extract-key]
(let [[book page]
(if (.contains "-" (extract-key assess-pro-acct))
(cstr/split (extract-key assess-pro-acct) #"-")
(cstr/split missing-book-page #"-"))]
(list (cstr/trim book) (cstr/trim page))))
Run Code Online (Sandbox Code Playgroud)
在以((if book ...
.开头的表达式周围有一组额外的括号。该if
表达式返回一个字符串,然后由于该字符串位于带有这两个括号外的列表的第一个位置,Clojure 尝试将该字符串作为函数调用。
括号在 Clojure 中非常非常重要。与 Fortran、C、C++、Java、Python 等语言中的算术表达式不同,在子表达式周围添加一组额外的括号是多余的,而且风格可能很糟糕,但无害,它改变了 Clojure 表达式的含义。