Thursday, March 31, 2016

Functional Programming for the Object-Oriented Programmer: My solution to the exercises of the sample chapter I found

I read about the book "Functional Programming for the Object-Oriented Programmer" and Clojure on Uncle Bob Martin's blog.

I am interested in learning about functional programming now because Uncle Bob says in his blog that a functional programming language will be the solution of creating software for a processor with many cores.

I am so excited about learning FP and Clojure so I'm going to post my solutions to the exercises of the sample chapter of the book mentioned above.

(I omitted some parts of the questions. Please download the sample chapter if you want to see the whole questions)


Exercise 1: Given what you know now, can you define a function second that returns the second
element of a list?

(def second (fn [list] (nth list 1)))


Exercise 2: Give two implementations of third, which returns the third element of a list.

(def third (fn [list] (nth list 2)))

(def third (fn [list] (first (rest (rest list)))))


Exercise 3: Implement add-squares.

(def square (fn [n] (* n n)))
(def add-squares (fn [& list] (apply +  (map square list))))


Exercise 4: The range function produces a sequence of numbers:
Using it and apply, implement a bizarre version of factorial that uses neither iteration nor recursion.

(def factorial (fn [n] (apply * (range 1 (+ n 1)))))


I did not do Excercise 5 :)


Exercise 6: Implement this function:
(prefix-of? candidate sequence): Both arguments are sequences. Returns true if the elements
in the candidate are the first elements in the sequence:

(def prefix-of? 
   (fn [candidate sequence] 
      (= candidate 
 (first (partition (count candidate) sequence)))))


Exercise 7: Implement this function:
(tails sequence): Returns a sequence of successively smaller subsequences of the argument.

(def tails 
   (fn [sequence]
      (map 
  drop
  (range 0 (+ 1 (count sequence)))
  (repeat (+ 1 (count sequence)) sequence))))


Exercise 8: In the first exercise in the chapter, I asked you to complete this function:

Mag-create siya ug list with one element inside which is also a list.

(after executing it on the command line)


Ahh I was wrong... "list" is a keyword (or a name of a function)

I googled the error -- I was wrong again -- the reason is because the the literal list is being used as a function. We cannot cast a literal list (I'm not sure if that is how we call it) into a function.