Merge pull request #8 from FrizzBolt/07-functions
Add solutions to section 07-functions
This commit is contained in:
commit
a815ae70ff
1 changed files with 12 additions and 10 deletions
|
|
@ -1,32 +1,34 @@
|
||||||
|
|
||||||
; "Calling a function is like giving it a hug with parentheses"
|
; "Calling a function is like giving it a hug with parentheses"
|
||||||
(= __ (square 9))
|
(= (square 9))
|
||||||
|
|
||||||
; "Functions are usually defined before they are used"
|
; "Functions are usually defined before they are used"
|
||||||
(= __ (multiply-by-ten 2))
|
(= (multiply-by-ten 2))
|
||||||
|
|
||||||
; "But they can also be defined inline"
|
; "But they can also be defined inline"
|
||||||
(= __ ((fn [n] (* 5 n)) 2))
|
(= 10 ((fn [n] (* 5 n)) 2))
|
||||||
|
|
||||||
; "Or using an even shorter syntax"
|
; "Or using an even shorter syntax"
|
||||||
(= __ (#(* 15 %) 4))
|
(= 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
|
||||||
|
|
||||||
; "Even anonymous functions may take multiple arguments"
|
; "Even anonymous functions may take multiple arguments"
|
||||||
(= __ (#(+ %1 %2 %3) 4 5 6))
|
(= 15 (#(+ %1 %2 %3) 4 5 6))
|
||||||
|
|
||||||
; "Arguments can also be skipped"
|
; "Arguments can also be skipped"
|
||||||
(= __ (#(* 15 %2) 1 2))
|
(= 30 (#(* 15 %2) 1 2))
|
||||||
|
|
||||||
; "One function can beget another"
|
; "One function can beget another"
|
||||||
(= 9 (((fn [] ___)) 4 5))
|
(= 9 ((fn [] ((fn [a b] (+ a b)) 4 5))))
|
||||||
|
|
||||||
; "Functions can also take other functions as input"
|
; "Functions can also take other functions as input"
|
||||||
(= 20 ((fn [f] (f 4 5))
|
(= 20 ((fn [f] (f 4 5))
|
||||||
___))
|
*)) ;; J - Mathematical operators in Clojure serve as functions.
|
||||||
|
|
||||||
; "Higher-order functions take function arguments"
|
; "Higher-order functions take function arguments"
|
||||||
(= 25 (___
|
(= 25 (#(% 5)
|
||||||
(fn [n] (* n n))))
|
(fn [n] (* n n))))
|
||||||
|
|
||||||
; "But they are often better written using the names of functions"
|
; "But they are often better written using the names of functions"
|
||||||
(= 25 (___ square))
|
(= 25 (defn square [n] (* n n)))
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue