user1259898
user1259898

Reputation: 83

Clojure Function Literals

I am doing Intro to Functions problem, but I don't quite understand what is going on? How are the 4 expressions below different? If they are all the same, why have 4 different syntaxes?

(partial + 5)
#(+ % 5)
(fn [x] (+ x 5))
(fn add-five [x] (+ x 5))

Upvotes: 8

Views: 1686

Answers (1)

dbyrne
dbyrne

Reputation: 61011

  • (fn [x] (+ x 5)) and #(+ % 5) - These two are completely equivalent, the latter just uses the dispatch macro to make the code a little more concise. For short functions, the #() syntax is usually preferred and the (fn [x]) syntax is better for functions which are a bit longer. Also, if you have nested anonymous functions, you can't use #() for both because of the ambiguity this would cause.

  • (fn add-five [x] (+ x 5)) - is the same as the above two, except it has a name: add-five. This can sometimes be useful, like if you need to make a recursive call to your function.*

  • (partial + 5) - In clojure, + is a variadic function. This means that it can accept any number of arguments. (+ 1 2) and (+ 1 2 3 4 5 6) are both perfectly valid forms. partial is creating a new function which is identical to +, except that the first argument is always 5. Because of this, ((partial + 5) 3 3 3) is valid. You could not use the other forms in this case.

*When making a recursive call from the tail position, you should use recur, however this is not always possible.

Upvotes: 19

Related Questions