Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 439
user1259898 Avatar asked Mar 09 '12 18:03

user1259898


People also ask

What does FN mean in Clojure?

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.

How do you create a function in Clojure?

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.

What does ->> mean in Clojure?

->> 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)))

How do you return a function in Clojure?

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 .


1 Answers

  • (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.

like image 153
dbyrne Avatar answered Sep 22 '22 03:09

dbyrne