假设我有一个字符串,我想按如下方式进行转换:
一种方法是这样的:
(defn my-function
[s]
(let
[
clean-string1 (clojure.string/replace s " " "")
clean-string2 (clojure.string/replace clean-string1 "." "")
clean-string3 (clojure.string/lower-case clean-string2)
]
;; ...
)
)
如何“链接”函数 clojure.string/replace
和 clojure.string/lower-case
以便
(clojure.string/replace s """")
的输出被馈送到(clojure.string/replace clean-string1 ".""")
并将其输出馈送到(clojure.string/lower-case clean-string2)
这样我就不需要中间变量 clean-string1
和 clean-string2
了吗?
最佳答案
您只需像使用任何语言一样进行操作。您要求函数组合,在数学或非 lisp 语言中看起来像 f(g(x))
。在 lisp 中当然是 (f (g x))
,但原理是一样的。
(require '[clojure.string :as s])
(s/lower-case (s/replace (s/replace s " " "") "." ""))
是最直接的答案。但是,将函数名称从它们的额外参数中移除到这种程度的嵌套是相当不愉快的,因此大多数人会改为写
(-> s
(s/replace " " "")
(s/replace "." "")
(s/lower-case))
这是同一回事,只是为了清晰起见,使用 ->
稍微打乱了表格。
https://stackoverflow.com/questions/68611024/