Clojure Programming/Examples/API Examples/Function Tools

From Wikibooks, open books for an open world
Jump to navigation Jump to search

fn[edit | edit source]

(map (fn [a] (str "hi " a)) ["mum" "dad" "sister"])
; => ("hi mum" "hi dad" "hi sister")

#()[edit | edit source]

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
user=> (sq 3)
9
user=> (map #(class %) [1 "asd"])      
(java.lang.Integer java.lang.String)
user=>

"lambda"[edit | edit source]

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

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

%[edit | edit source]

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.

complement[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
user=> (single-digit 9)
true
user=> (single-digit 10)
false
user=> (def multi-digit (complement single-digit))
#'user/multi-digit
user=> (multi-digit 9)
false
user=> (multi-digit 10)
true