簡體   English   中英

在Clojure中with-redefs和with-redefs-fn有什么區別?

[英]What is the difference between with-redefs and with-redefs-fn in Clojure?

我想了解with-redefswith-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-redefswith-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM