clojure-koans/07_functions.clj

35 lines
1.1 KiB
Clojure
Raw Normal View History

; "Calling a function is like giving it a hug with parentheses"
2016-02-28 23:33:46 +00:00
(= (square 9))
; "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
; "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
; "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
; "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
; "Arguments can also be skipped"
2016-02-28 23:33:46 +00:00
(= 30 (#(* 15 %2) 1 2))
; "One function can beget another"
2016-02-28 23:33:46 +00:00
(= 9 ((fn [] ((fn [a b] (+ a b)) 4 5))))
; "Functions can also take other functions as input"
(= 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
; "Higher-order functions take function arguments"
2016-02-28 23:33:46 +00:00
(= 25 (#(% 5)
(fn [n] (* n n))))
; "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)))