Exercise 07 Functions - MikeyYeahYeah/clojure-koans GitHub Wiki

Exercise 07 - Functions

Using the following functions in the example below

(defn multiply-by-ten [n]
  (* 10 n))

(defn square [n] (* n n))

A few quick notes:

  • defn square
    • This defines the name of the function. It is called square in this case
  • [n]
    • This is the parameter being passed in called n
  • (* n n)
    • This say multiply the value passed in via parameter n by itself

Calling Defined Functions

(square 9)
  ;;=> 81

(multiply-by-ten 2)
  ;;=> 20

Creating Functions Inline AKA Anonymous Functions

Note: An anonymous function is a function that doesn’t have a name. A pretty great explanation of anonymous functions here.

You can create inline functions using the following syntax:

;; Full Syntax
((fn [n]) (* 5 n) 2))
	;;=> 10

;; Shortened Syntax
(#(* 5 %) 2)
	;;=> 10

;; Calling multiple arguments using anonymous functions
(#(+ %1 %2 %3) 4 5 6)
	;;=> 15

;; You can also skip arguments
(#(* 15 %2) 1 2)
	;;=> 30

You can also use functions within functions

;; This one is interesting.  This function has no parameters.  When it is evaluated, it retruns the + function.  The 4 and 5 get passed into the + function for an answer of 9.  
((fn [] +)) 4 5)
	;;=> 9
 
;; In this one, the * function is being passed in as argument f.  This is then replaced and produces an answer of 20.   
 ((fn [f] (f 4 5)) *)
 	;;=> 20

Higher Order Functions

The simplest way to explain a higher order function, is a function that takes a function as a parameter. The example in the clojure koan is pretty weird right now. Hoping it will make more sense in Exercise 08. Lets try it now though.

(= 25 (___
		(fn [n] (* n n))))

;; Lets break this apart.  We have an anonymous function that will square a number.
(fn [n] (* n n))

;; We want to pass this function... as an argument... in a function.
(fn [x] (x 5))

;; So what ends up happening is
x = (fn [n] (* n n))

;; Expanded out it looks like:
(fn [x] ((fn [n] (* n n)) 5))

;; This essentially boils down to
(fn [n] (* n n)) 5)

;; Which boils down to
(* 5 5)

;; Which matches our final answer of
25

If you want to make this more sane....

(defn square [n] (* n n))

((fn [x] (x 5)) square)

;; The value of x becomes the function called square
x = square

;; Square is in the expression and evaluated
fn [x] (square 5)

;; This is teh definition of square written out  
(fn [n] (* n n) 5)

;; The 5 is passed in as an argument
(* 5 5)

;; And produces your final answer
25