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?
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.
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.
Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.
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.
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)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With