2014-01-26 00:04:22 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Calling a function is like giving it a hug with parentheses"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= (square 9))
|
2013-03-04 23:51:31 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Functions are usually defined before they are used"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= (multiply-by-ten 2))
|
2010-02-09 04:57:08 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "But they can also be defined inline"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 10 ((fn [n] (* 5 n)) 2))
|
2010-02-09 04:57:08 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Or using an even shorter syntax"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 60 (#(* 15 %) 4)) ;; J - This is an important bit of sugar to memorize.
|
|
|
|
|
;; To make it easy, '#' initiates the declaration of an anonymous function
|
|
|
|
|
;; and % is the argument. So, in this case, # replaces 'fn [n]' and '%' replaces n
|
2010-02-09 04:57:08 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Even anonymous functions may take multiple arguments"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 15 (#(+ %1 %2 %3) 4 5 6))
|
2010-11-05 22:33:06 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Arguments can also be skipped"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 30 (#(* 15 %2) 1 2))
|
2013-07-22 15:55:09 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "One function can beget another"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 9 ((fn [] ((fn [a b] (+ a b)) 4 5))))
|
2013-03-04 23:51:31 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Functions can also take other functions as input"
|
2013-03-04 23:51:31 +00:00
|
|
|
(= 20 ((fn [f] (f 4 5))
|
2016-02-28 23:33:46 +00:00
|
|
|
*)) ;; J - Mathematical operators in Clojure serve as functions.
|
2010-02-09 04:57:08 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "Higher-order functions take function arguments"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 25 (#(% 5)
|
2013-03-04 23:51:31 +00:00
|
|
|
(fn [n] (* n n))))
|
2010-11-03 03:29:45 +00:00
|
|
|
|
2016-02-27 02:33:05 +00:00
|
|
|
; "But they are often better written using the names of functions"
|
2016-02-28 23:33:46 +00:00
|
|
|
(= 25 (defn square [n] (* n n)))
|