Reputation:
Could any one explain why in the following code the name of the function acts in the first part as a *
(multiplier)?
(defn bar
([a b] (bar a b 100))
([a b c] (* a b c)))
Giving bar
two args (bar 2 3)
yields (* 2 3 100)
Upvotes: 0
Views: 71
Reputation: 50057
If might be easier to see what's going on if you reformat it slightly:
(defn bar
([a b] (bar a b 100))
([a b c] (* a b c)))
This is a function with multiple arity - that is, it accepts more than one set of arguments. The first definition accepts two arguments named a
and b
, and second definition accepts three arguments named a
, b
, and c
. When the first definition of the function is invoked it turns around and invokes the second definition of the function, passing in the a
and b
arguments which were given to the first definition, and sending the constant value 100 as the third argument. The second definition of bar
simply takes the three arguments it's given and multiplies them together using (* a b c)
.
Hope this helps.
Upvotes: 5
Reputation: 144206
You have defined a function with two overloads - the first takes two arguments and the second three. The two-argument overload simply calls the three-argument version with 100 as the third argument.
Upvotes: 2