Calling Clojure higher-order functions

吃可爱长大的小学妹 提交于 2019-12-08 17:18:55

问题


If I define a function that returns a function like this:

(defn add-n
  [n]
  (fn [x] (+ x n)))

I can then assign the result to a symbol:

(def add-1 (add-n 1))

and call it:

(add-1 41)
;=> 42

How do I call the result of (add-n 1) without assigning it to a new symbol? The following produces this output:

(println (add-n 1))
#<user$add_n$fn__33 user$add_n$fn__33@e9ac0f5>
nil

The #<user$add_n$fn__33 user$add_n$fn__33@e9ac0f5> is an internal reference to the generated function.


回答1:


Easy:

(println ((add-n 1) 41))

The output you saw is a function definition. Putting it between round brackets and adding a parameter is enough to call it.



来源:https://stackoverflow.com/questions/6008775/calling-clojure-higher-order-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!