1

06_function.clj contains this question, I can't figure out why there is an extra pair of () in position 1 and 2, since position 3 already has brackets wrapped up.

"One function can beget another"
  (= 9 (
        (   <---- 1
         (fn [] (fn [a b] (+ a b)))  <----3
         )  <-----2
        4 5))

2 Answers 2

5
(fn [a b] (+ a b))

is a function that takes 2 arguments and returns their sum, let's substitute if with name fun1

(fn [] fun1) 

is a function that takes nothing and returns function object fun1. Let's call this new function fun2

( 
  fun2
) 

here we call fun2, which, as we previously discussed, returns function fun1

(
  fun1
4 5)

here we call fun1 (returned from (fun2)) with 2 arguments - 4 and 5. This gives us 9

(= 9
  9) 

and finally we check equality of 2 numbers. They are actually equal.

The main thing you should understand here is that functions in Clojure are also first-class citizens. You may produce them (like fun1), pass them to other functions and return from them (like we returned fun1 from fun2). So each layer of ( and ) is just another call to a function (possibly returned from some other function).

Sign up to request clarification or add additional context in comments.

Comments

2

It's there to evaluate the function created by outer fn.

So, in turn:

(fn [a b] (+ a b)

creates the inner function that sums it's arguments

(fn [] (fn [a b] (+ a b))

creates the outer function with taking zero arguments and returning a function that sums it's arguments.

(   
     (fn [] (fn [a b] (+ a b)))  
)  

forces evaluation of the outer function (and returns it's result - a function that sums two values).

Remember that when you see parentheses in lisps the first thing that should pop in your mind is that it's an application of the function/form/macro to it's arguments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.