I'd like to call an anonymous function which is not using the shorthand notation from another anonymous function.
Doing the following isn't working because the last evaluation is returned:
user> ((fn [x] (fn [y] (inc y)) x) 3)
3
Now I'd like to have a way to call the inside anonymous function from the outer one.
I managed to make it work by doing this but it looks complicated:
user> ((fn [x] (let [f (fn [y] (inc y))] (f x))) 3)
4 ;; good, 4 is the result I want here
Is there an easier way to nest anonymous functions?
Let's break that first line up:
((fn [x]
(fn [y] (inc y)) ; construct an anonymous function
x) ; return the outer parameter
3)
Note that the inner function is never used.
What you seem to want to do:
((fn [x]
((fn [y] (inc y)) x))
3)
I'd strongly recommend using the let form to improve the clarity of the code, e.g.
(let [f (fn [y] (inc y))
g (fn [x] (f x))]
(g 3))
I would even have the other function to accept the former.
(let [f (fn [y] (inc y))
g (fn [h x] (h x))]
(g f 3))
or even as follows:
(let [f (fn [y] (inc y))
g (fn [h x] (h x))
gf (partial g f)]
(gf 3))
It makes the reading and hence understanding of the function much easier. Even with let I would not stop here and work on another better function.
After a bit of thought I think there's no need to define a one-arg function f when inc does that. Also one might get carried away using the reader's anonymous function literal and the let form becomes:
(let [f inc
g #(% %2)
gf (partial g f)]
(gf 3))
But the more I think about it, the less I understand the problem.
Could you describe what you really want to achieve?
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