Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Clojure higher-order functions

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.

like image 974
Ralph Avatar asked May 15 '11 13:05

Ralph


People also ask

What is difference between higher order functions and callbacks?

Higher-Order Functions(HoF): A function that takes another function(s) as an argument(s) and/or returns a function as a value. Callback Functions(CB): A function that is passed to another function.

What does FN mean in Clojure?

First Class Functions They can be assigned as values, passed into functions, and returned from functions. It's common to see function definitions in Clojure using defn like (defn foo … ​) . However, this is just syntactic sugar for (def foo (fn … ​)) fn returns a function object.

How do you return a function in Clojure?

There isn't a return statement in Clojure. Even if you choose not to execute some code using a flow construct such as if or when , the function will always return something, in these cases nil .


1 Answers

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.

like image 56
Maurits Rijk Avatar answered Sep 21 '22 21:09

Maurits Rijk