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))
First Class Functions They can be assigned as values, passed into functions, and returned from functions. It's common to see function definitions in Clojure using defn like (defn foo … ) . However, this is just syntactic sugar for (def foo (fn … )) fn returns a function object.
A function is defined by using the 'defn' macro. An anonymous function is a function which has no name associated with it. Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type.
->> is the "thread-last" macro. It evaluates one form and passes it as the last argument into the next form. Your code is the equivalent of: (reduce str (interpose ", " (map :subject scenes)))
There isn't a return statement in Clojure. Even if you choose not to execute some code using a flow construct such as if or when , the function will always return something, in these cases nil .
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With