In Clojure, is it possible to define an anonymous function in an anonymous function?

For example, solving the following problem

http://projecteuler.net/problem=5

I came up with the following solution

(defn div [n] (= 0 (reduce + (map #(mod n %) (range 1 21))))) (take 1 (filter #(= true (div %)) (range 20 1e11 20))) 

Suppose for some golf game I want to combine the first line as an anonymous function into the second line. Does the language support this language?

+6
source share
2 answers

Yes, but this is not possible, but you cannot embed forms-reader-macro #() , you need to use form (fn) .

For instance:

 (#(#(+ %1 %2) 1) 2) 

does not work, because there is no way to refer to the arguments of external anonymous functions. This reads as an external function that takes two arguments, and the internal function takes zero arguments.

But you can write the same with (fn...) s:

 user=> (((fn [x] (fn [y] (+ xy))) 1) 2) 3 

You can also use the #() form for one of two anonymous functions, for example:

 user=> (#((fn [x] (+ x %)) 1) 2) 3 

Thus, you can embed your div function as follows (note that we had to change the form #() passed to the map form to the (fn) form):

 #(= true (= 0 (reduce + (map (fn [x] (mod % x)) (range 1 21))))) 
+17
source

You can rewrite your solution much easier and more efficiently (x2 faster!)

 (defn div [n] (every? #(= 0 (mod n %)) (range 1 21))) (take 1 (filter div (range 20 1e11 20))) 

The reason it is more effective is because every? It will not move throughout the list, but will stop when one of the list items is false.

0
source

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


All Articles