Saturday, May 17, 2014

Clojure Koans Answers and Explanations - 6 - functions

Here is the solution for Clojure Koans on functions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1

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

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

; defn is equivalent of def in Python, Ruby
; is the same as FUNCTION in PL SQL, MYSQL UDF
; is same as subroutine in Perl
; is same as function in Pascal, Fortran, PHP
; there are no close equivalents in C/C++/Java
; is a shorthand of def + fn in Clojure

; In clojure args to function are passed in []
; body is of course defined in ()

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


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= __ ((fn [n] (* __ n)) 2))
; here the function has no name and is anonymous function
(= (multiply-by-ten 2) ((fn [n] (* 10 n)) 2))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= __ (#(* 15 %) __))
; there is an alternate syntax
; a kind of shorthand
; the form preferred by experienced Clojurist
(= 30 (#(* 15 %) 2))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= __ (#(+ %1 %2 %3) 4 5 6))
; anonymous functions can take arguments as well
; this anonymous function function
; takes 4 5 6 as args and applies + over them
(= 15 (#(+ %1 %2 %3) 4 5 6))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
(= __ ((fn []
           ((fn [a b] (__ a b))
            4 5))))
; this is the practice rather than exception
; in lisp and clojure
(= 20 ((fn []
           ((fn [a b] (* a b))
            4 5))))
; a serious question would have been this.
; removing a set of paren
; stops the anonymous function from executing
(= __ (fn []
           ((fn [a b] (* a b))
            4 5)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;7
(= 25 (___
         (fn [n] (* n n))))
; a higher order function taking another function as arg
; here the anonymous function (fn [n] (* n n) needs to be passed to
; another function such that the final result is 25
 (= 25 ((fn [aFun] (aFun 5))
         (fn [n] (* n n))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;8
(= 25 (___ square)))
; lets use the square function defined in the beginning
; the function square is passed as an arg to the anonymous function
; which does nothing but invoke the function.
(= 25 ( (fn[aFun](aFun 5)) square))



No comments:

Post a Comment