Function definition with "extra" brackets

Can someone explain to me why

((fn ([x] x)) 1) 

works and returns 1? (There is one "extra" set of brackets after fn). Shouldn't it be next?

 ((fn [x] x) 1) 

Besides,

 ((fn (([x] x))) 1) 

(2 "extra" sets of parentheses) with "CompilerException System.ArgumentException: parameter declaration ([x] x) must be a vector." Why?

Thanks!

+4
source share
1 answer

An additional set of brackets allows you to define a function with a variable number of arguments. The following example defines a function that can take one argument or two arguments:

 (defn foo ([x] x) ([xy] (+ xy))) 

You can see this as a definition of two functions under the same name. The corresponding function will be called depending on the number of arguments that you provide.

If you define a function with a fixed number of arguments, the following two forms are equivalent:

 (defn bar ([x] x)) 

and

 (defn baz [x] x) 

With that in mind, you can understand the compiler exception. You are trying to define a function as follows:

 (defn qux (([x] x))) 

When using an additional set of parentheses, the closure expects the first element inside the partensis to be a vector (in brackets). However, in this case, the first element is ([x] x) , which is a list, not a vector. This is the error you are getting.

+10
source

Source: https://habr.com/ru/post/1484922/


All Articles