[英]What is the difference between with-redefs and with-redefs-fn in Clojure?
我想了解with-redefs
和with-redefs-fn
之間with-redefs
。
具體的例子可以很好地理解fns行為。
它們基本相同,主要區別在於with-redefs
允許你明確地寫出正文(比如在let
),而with-redefs-fn
需要一個函數作為參數,所以你可能需要包裝你的內容想要一個lambda。 另外, with-redefs
允許你使用向量(再次,像let
)提供綁定,而with-redefs-fn
想要一個地圖。 我認為這兩種差異都只是膚淺的。
例如
(with-redefs [http/post (fn [url] {:body "Goodbye world"})]
(is (= {:body "Goodbye world"} (http/post "http://service.com/greet"))))
VS
(with-redefs-fn {#'http/post (fn [url] {:body "Goodbye world"})}
(fn [] (is (= {:body "Goodbye world"} (http/post "http://service.com/greet")))))
事實上, with-redefs
是with-redefs-fn
,基本上只是在將所有內容傳遞給with-redefs-fn
之前將主體包裝在一個匿名函數中: https : //github.com/clojure/clojure/blob /e3c4d2e8c7538cfda40accd5c410a584495cb357/src/clj/clojure/core.clj#L7404
我會忽略with-redefs-fn
並僅使用with-redefs
因為它更簡單並具有相同的能力。 另外,請注意符號#'http/post
要求您使用var for http/post
,而不是函數本身。
有關Clojure var
如何工作的描述,請參閱此問題: 何時使用Var而不是函數? 它類似於C指針。
在clojure中,當你看到foo
,它就是一個符號。 當你看到#'foo
,它是(var foo)
一個快捷方式,它是一個“特殊形式”(即內置的Clojure,而不是常規函數),它返回foo
指向的var
。 var
依次指向foo
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.