Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the leading arrow in a name mean in clojure

Tags:

Learning Clojure I came across code like below:

=> (defrecord Person [name, age]) user.Person => (->Person "john" 40) #user.Person{:name "john", :age 40} => (Person. "tom" 30) #user.Person{:name "tom", :age 30} 

the question is, what does the leading arrow(i.e., ->) in the ->Person mean ? It's a reader macro or what ? I see no description of it in the reader section of clojuredoc. Further, what is the difference between ->Person and Person. ?

like image 203
John Wang Avatar asked Aug 21 '12 03:08

John Wang


Video Answer


2 Answers

It has no syntactic meaning. It is just part of the symbol name. In Lisps, the arrow -> (or even just '>') is often used to imply conversion of, or casting of, one type into another. In the macro expansion of the defrecord:

(macroexpand '(defrecord Person [name age])) 

you can see that it defines ->Person as a function that calls the Person constructor. ->Person (the function) may be more convenient for you to use than Person. (the direct call to the Java constructor) as you can pass it as an argument to other functions, capture it in a variable and use it, etc:

(let [f ->Person]   (f "Bob" 65)) 

Compare that to:

(let [f Person.]   (f "Bob" 65)) 

Which is syntactically invalid.

like image 72
Kyle Burton Avatar answered Oct 03 '22 08:10

Kyle Burton


Obviously not in your specific example, but in the general context this operator -> is called the threading operator and is considered one of the thrush operators. Along with its cousin the ->> operator, these operators are quite useful when you need to have code appear more clearly, especially when feeding the output of functions as parameters to another function. Both operators are macros. Here's another SO post concerning both operators.

I have not yet had cause to use the ->, but did need ->> to make sense of code that needed to compute intermediate values and put them all into one function call.

Here is another explanation.

like image 22
octopusgrabbus Avatar answered Oct 03 '22 07:10

octopusgrabbus