Nested Anonymous Functions in Clojure

Is a nested anonymous function legal or not? I wrote the following for problem number 107 4clojure:

(fn [n] #(reduce * (repeat n %))) 

which passed all three tests, however, when I try to use it with test 3 in repl, I get an IllegalStateException that says that nested # () s are not allowed:

 IllegalStateException Nested #()s are not allowed clojure.lang.LispReader$FnReader.invoke (LispReader.java:628) CompilerException java.lang.RuntimeException: Unable to resolve symbol: n in this context, compiling:(NO_SOURCE_PATH:1:44) RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221) RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221) CompilerException java.lang.RuntimeException: Unable to resolve symbol: % in this context, compiling:(NO_SOURCE_PATH:0:0) RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221) RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221) RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221) RuntimeException Unmatched delimiter: ) clojure.lang.Util.runtimeException (Util.java:221) 

Why can't this be passed to repl, but to 4clojure?

+5
source share
1 answer

Nested anonymous functions are fine. But you cannot embed the reader macro # (), because then it is not defined correctly - we cannot know if through %1 programmer had in mind the first argument for the external function literal or the first argument for the internal function literal,

You will need to enter the internal function "longhand" (using fn ) if you want to evaluate the entire test form.

 (fn [n] (fn [m] (reduce * (repeat nm)))) 

He is working on 4Clojure, probably because they evaluate the form you submit before embedding it in test forms. Thus, macroC # () has already been expanded (to fn* ) when evaluating the test form.

+10
source

All Articles