Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure, is it possible to define an anonymous function within 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 golfing fun I wish to merge the first line as an anonymous function into the second line. Does the language support this?

like image 875
deltanovember Avatar asked Feb 09 '12 10:02

deltanovember


People also ask

How do you define an anonymous function?

An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.

Can we assign an anonymous function?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.

Is it valid to pass an anonymous function?

Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

What is the important properties of an anonymous function?

An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression.


1 Answers

Yes it does, but you cannot nest the #() reader-macro forms, you have to use the (fn) form.

For example:

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

does not work, because there's no way to refer to the arguments of the outer anonymous functions. This is read as the outer function taking two arguments and the inner function taking zero arguments.

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

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

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

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

So you can inline your div function like this (notice that we had to change the #() form passed to map to a (fn) form):

#(= true (= 0 (reduce + (map (fn [x] (mod % x)) (range 1 21)))))
like image 131
liwp Avatar answered Nov 09 '22 06:11

liwp