3

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?

2 Answers 2

8

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

ooooh gotcha. By wrapping the (fn ...) x inside a list I'm returning the evaluation of that instead of returning the outer parameter. Why oh why didn't I think of that! It doesn't seem like much but your answer helps me actually a lot! Thanks : )
5

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?

2 Comments

what I want to achieve is understand better how the language works ; )
Hope you did with my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.