Clojure let, apply, and multi-arity functions.


;; examples of let:
(let [x 5
      y (+ x 2)]
  [x y])

;; multi-arity functions:
(defn add5
  "add5 adds 5 to the sum of its arguments. Can be called with 0-2 args"
  ([] 5)
  ([x] (+ x 5))
  ([x y] (+ x y 5)))

(add5)
(add5 3)
(add5 3 4)

;; a fucntion that takes any number of arguments:
(defn add5-to-any
  "adds 5 to the sum of its arguments. Can be called with any number of arguments"
  [& args]
  (println args) ;; args is a sequence
  (+ 5 (reduce + args)))

(add5-to-any)
(add5-to-any 3 5 6 1 2)

;; apply is a useful function that allows treating a sequence as
;; separate function arguments

;(+ '(1 2 3)) ;; this is an error since + doesn't work on a sequence
(apply + '(1 2 3))
(apply + 5 '(1 2 3)) ;; it also can take its arguments as a mix of values and sequences

;; rewriting the previous example:
(defn add5-to-any-2
  "adds 5 to the sum of its arguments. Can be called with any number of arguments"
  [& args]
  (apply + 5 args))

(add5-to-any-2)
(add5-to-any-2 3 5 6 1 2)

;; destructuring arguments, pattern-matching:
(defn f
  "illustarting destructuring of a vector"
  [[x & xs]] (str "The first vector item is " x ", the rest are " xs))

(f [2 3 4])

(f []) ;; x and xs are bound to nil, ignored when forming a string

CSci 4651 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.