![](/img/trans.png)
[英]how to understand such a macro definition in the book programming Clojure 2nd 's page 173?
[英]Functional Programming with Clojure
大師
這是一個問題:我正在研究一個涉及將函數傳遞給函數的clojure程序。
我有類似的東西:
(defn funct-op [args]
((first args)
(second args)
(last args) )
(funct-op '(+ 2 2))
我如何哄騙funct-op給我4而不是我目前得到的2 ? 隨着項目的進展,我可能需要將函數傳遞給宏。 關於如何做到這一點的任何提示? 謝謝你的幫助!
什么是funct-add
真的應該做什么? 如果它是什么(funct-add '(- 2 2))
?
無論如何,考慮申請 ,甚至包裝:
(defn apply-wrapper [args]
(apply (first args) (rest args)))
; note use of of the [...] form
(apply-wrapper [+ 2 2]) ; => 4
(apply-wrapper [- 2 2]) ; => 0
比較這些形式可能具有啟發性:
(+ 1 2) ; 3
'(+ 1 2) ; (+ 1 2)
[+ 1 2] ; [#<core$_PLUS_ clojure.core$_PLUS_@a8bf33> 1 2]
注意如何評估最后一個; 它不僅僅是一個“文字列表” - 再也沒有符號了! :-)
快樂的編碼。
為了將'+'轉換為函數,您可以使用resolve。 這應該適用於核心功能,但您可能需要ns-resolve來實現自定義功能。 然后,您可以使用apply將其余參數傳遞給該函數。
(defn funct-add [args] (apply (resolve (first args)) (rest args)))
不確定你的最終目標是什么,但我認為這是你正在尋找的答案。
我不確定,這些東西?
(defn funct-op [f list]
(apply f list))
(funct-op + '(1 2));=>3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.