4
votes

Are the -> and ->> macros only to make the code more readable or they have also other specific functions?

1

1 Answers

7
votes

The thread-first (->) and thread-last (->>) are there to make code more readable. But that's already pretty important !

It allows to un-nest function calls (example taken from clojuredocs) :

;; Arguably a bit cumbersome to read:
user=> (first (.split (.replace (.toUpperCase "a b c d") "A" "X") " "))
"X"

;; Perhaps easier to read:
user=> (-> "a b c d" 
           .toUpperCase 
           (.replace "A" "X") 
           (.split " ") 
           first)

It also allows you to put the emphasis on something. For instance, consider :

(-> {... }
    ...
    ...
    (count)) 

(count (...(... {...})))

In the first example, it is very clear that you start with a map, and then do something to it. In the second, it is clear that you count something.

The preference depends on what you want to put forward.

Also, the choice of -> vs ->> is a clear visual indicator : are you operating or not on collections ? This is made immediately obvious (this is a convention in Clojure to have the collection as a last parameter).

So yes, it is "only" readability, but that is a very important part of building programs, and Clojure gives you tools to make your code read naturally. When choosing one solution, I try to consider the way Clojure will be read.