# Clojure: Function Chaining

In Clojure, there's a special syntax to chain functions. (called pipe in unix shell. [see Unix Pipe as Functional Language])

For example, `(f2 (f1 x))`

can be written as
`(-> x f1 f2)`

.

`->`

is a macro for “pipe”. It transforms syntax, from a linear notation into nested notation.
This is also known as “function chaining”.
Clojure calls this “threading”.
clojure.core/->

`(-> x f1)`

is equivalent to`(f1 x)`

`(-> x f1 f2)`

is equivalent to`(f2 (f1 x))`

`(-> x f1 f2 f3)`

is equivalent to`(f3 (f2 (f1 x)))`

;; example of using -> (defn f1 "append \"1\" to a string" [x] (str x "1")) (defn f2 "append \"2\" to a string" [x] (str x "2")) (f1 "a") ; "a1" (f2 "a") ; "a2" ;; pipe arg to function (-> "x" f1) ; "x1" ;; pipe. function chaining (-> "x" f1 f2) ; "x12"

• `->>`

is similar to `->`

, but pass arg into the last argument position of function. clojure.core/->>

## Pass Binding

`(as-> `

evaluate each form in turn, such that in `expr` `name` `form1` `form2` `form3` …)`form1` the `name` has value of `expr`, and in `form2` the `name` has the value of `form1`'s result, etc. Returns the result of the last form.

(as-> 4 x (list 3 x)) ; returns (3 4)

(as-> "a" x (list 1 x) (list 2 x) (list 3 x) (list 4 x) (list 5 x)) ;; returns ;; (5 (4 (3 (2 (1 "a")))))

Patreon me $5. Ask me question on patreon