Defn assignment in Clojure

I am a little puzzled by the role of defn. If fn created anonymous functions, I could understand the need for a construct that combines the functions def and fn, but fn can also create named functions. At least in repl, I don't see how this usage differs from defn.

+4
source share
2 answers

When you specify a symbol for the name fn , it is bound only to the function definition to the function object itself. This allows anonymous functions to call themselves ( Clojure - special forms ).

So, to create a function with fn associated with a globally accessible name, you should use

 (def somename (fn ...body... 

and defn is just a shortcut to this.

 (defn somename ...body... 

In response to your comment, from fresh repl:

 Give me some Clojure: > (fn foo [] (+ 1 3)) #<sandbox31764$eval31779$foo__31780 sandbox31764$eval31779$foo__31780@12eae8eb > > (foo) java.lang.RuntimeException: Unable to resolve symbol: foo in this context > (defn foo [] (+ 1 3)) #'sandbox31764/foo > (foo) 4 > 

As you can see, I cannot call the foo function created with fn because it is not bound to Var.

+6
source

The main difference is that defn creates a global name, wherees fn creates only a lexical one. The global name is also var, as it is ultimately created using def . The name you can give an anonymous function is not var and is only within that function. This is basically so that a function can be recursive.

+1
source

Source: https://habr.com/ru/post/1493461/


All Articles