Clojure Programming/Examples/API Examples/Function Tools

From Wikibooks, open books for an open world
Jump to navigation Jump to search
(map (fn [a] (str "hi " a)) ["mum" "dad" "sister"])
; => ("hi mum" "hi dad" "hi sister")

See the reader page, (Macro characters -> Dispatch -> Anonymous function literal) for an explanation of the '%' and other characters used to refer to function arguments.

user=> (def sq #(* % %))
user=> (sq 3)
user=> (map #(class %) [1 "asd"])      
(java.lang.Integer java.lang.String)


[edit | edit source]

Use fn, or even better there is a custom syntax to create an anonymous function:

(map #(str "hi " %) ["mum" "dad" "sister"])

Represents an optional argument to an unnamed function:

#(+ 2 %)
#(+ 2 %1 %2)

Arguments in the body are determined by the presence of argument literals taking the form %, %n or %&. % is a synonym for %1, %n designates the nth arg (1-based), and %& designates a rest arg.


[edit | edit source]

Usage: (complement f)

Takes a fn f and returns a fn that takes the same arguments as f, has the same effects, if any, and returns the opposite truth value.

user=> (defn single-digit[x] (< x 10))
user=> (single-digit 9)
user=> (single-digit 10)
user=> (def multi-digit (complement single-digit))
user=> (multi-digit 9)
user=> (multi-digit 10)