English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Developing a Clojure Edge



Can be passed

(map inc [1 2 3])

-> (2 3 4)

and returned

(defn make-adder [x]

 #(+ x %))

Have closure

A closure is a function which captures its environment

(let [x (atom 1)]

 (defn incx []

   (swap! x inc))

 (defn addx [y]

   (+ @x y)))

These functions capture x and use it when called outside the let scope.

type inference


Building blocks

Better to have 10 objects with 100 functions that can operate on them than 100 objects with 10 functions that can operate on them.


partial application

(partial * 5)

returns a function which will take additional arguments

((partial *5) 2 3)

=> 30

This is an alternative syntax to #(* 5 %), however note that it allows for vardic capturing where the anonymous syntax does not.  Some functional programmers prefer partial style, in Clojure the norm seems to be to use anonymous functions as it is less characters.  Clojure built-in functions typically take arguments in an order that foils partial application, so using anonymous functions consistently is preferable.

comp is shorthand for composition.

(comp reverse sort)

returns a function which will sort then reverse its input.

((comp reverse sort) [2 1 3])

=> (3 2 1)

This is equivalent to writing

#(reverse (sort %))

But again can be convenient when used inside an anonymous function (anonymous functions do not support nesting) or when you do not wish to fix the arguments.

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.