Thursday, 28 February 2013

Code ~> Functional Programming ~> Clojure

I'm playing with Clojure! :)

So I have this thing - I want to learn at least two programming languages every year. Last year I learnt Ruby and Python. I was a bit confused what languages to play with this year. A friend of mine suggested Clojure and I am happily diving in! I will decide with time the other language I will learn. This post will about writing simple Clojure code.

Step one is getting a good Clojure guide. A simple Google search will sort you out. I am using "Programming Clojure Second Edition, The Pragmatic Programmers". I'm loving the book! If you want to get your hands dirty with some code, step two is installing a Java Runtime and Leiningen. Google around how to install a Java Runtime for your OS and visit the Leiningen GitHub page on details of how to get leiningen running on your machine. Leiningen is a tool for managing your Clojure dependencies and launching tasks against your code. Someone wrote, Leiningen is for automating Clojure projects without setting your hair on fire. If your're following, you should know where it's from! ;)

You can test out this code by running a Clojure REPL. When you have Leiningen up and running, it has a REPL launch script. Run lein repl. Now you are all good to go.

We're going to write a simple function, favourite-activity that takes your name and favourite activity as arguments and prints out your-name's favourite activity is favourite-activity! This should be fun! To define a function is Clojure, we use the key word defn followed by the function name, the parameters and finally the body. Here is our function:

user=> (defn favourite-activity [name activity] (str name "'s favourite activity is " activity "!"))

This is how we we will call the function:

user=> (favourite-activity "Martha" "coding")
-> "Martha's favourite activity is coding!"

Nice! If that syntax excites you as much as it excites me, then get down to coding in Clojure! I will be going into details of the language in late posts.

And if Clojure excites you, then you need to play with some LISP. I recommend reading Structure and Interpretation of Computer Programs, which was recommended to me by another friend.

Cultivate the garden of your mind.



Wednesday, 27 February 2013

Code ~> Python ~> Recursion

Today, I spent some time doing MITx: 6.00x Introduction to Computer Science and Programming on edx. The course is in Python, so I am polishing my Python syntax in the process. :)

As the title suggests, the topic today was on recursion. This basically means breaking a problem into a smaller easier problem to solve, then solving it from at point. I am going to use a simple example to explain this concept. In functions, the functioned being defined is applied within it's own definition. 

Let us pretend that Python did not have a build in function to do multiplication, but had a build in function to do addition. We are doing to use the addition function, so come up with our own multiplication function.

We will first solve the problem using an iterative function, then will use a recursive function.

So to break down multiplication to simple terms, when we multiply a number n by a number m, we are simply adding up m times of n, or adding up m copies of n. So this means, n * m = n + n  (m -1). That makes the problem much simpler! Let us break it down one more step: n + n  (m -1) = n + n + n (m - 2).  We could go on doing this until it is the basic addition I mentioned earlier. Let us now do this in Python.

Iterative function

def multiplierI(a, b):
    """takes two positive integers, and returns the product of the two"""
    result = 0
    while b > 0:
        result += a
        b -= 1
    return result


Recursive function


def multiplierR(a ,b):
    """takes two positive integers and returns the product of the two"""
    if b == 1:
        return n
    elif b == 0:
        return 0
    else:
        return a  + multiplierR(a, b - 1)

So how does this function work, you may ask.

Let me call it with two arguments, 1 and 2.
multiplierR(1, 2)

I shall now attempt to explain the different environments that are involved in the recursive function so that you see that even though there are no assigned state variables (eg result in the iterative function), that are clearly being updated, we will not be stuck it an infinite loop. I know that what's going on is pretty straight forward to programmers, even beginners, but I have fun explaining stuff, so here goes.

When we call multiplierR(1, 2), the interpreter looks up multiplierR() in the global environment, and sees that it is a procedure object taking two parameters. It creates another environment where it binds a(the first parameter) to 1 and b(the second parameter) to 2. In the body of multiplierR(), we check whether b is 1 or 0, it's neither cause it's bound to 2. We then move down to else statement which returns a added to another call to multiplierR(), this time passing in (a, b-1), which in our case is (1, 1). The interpreter again looks up multiplierR(), finds the procedure object. It create a third environment where it binds a(the first parameter) to 1, and b(second parameter) to 1. In the body, we check if b is equal to 1, yes it is, so we return a, which is 1 in our case. Remember, that this second call if from the point where it is called within the function itself. This is the line a + multiplierR(a, b - 1). multiplierR(a, b - 1) returns a, breaking this down to a + a, which is 1 + 1 in our case.

I have used small integers to avoid going over all the process again and again. But please not that b in the case where b is a large number, say 5, the return value of the call to multiplierR() in all the different environments are there, though not accessible to us, so when b is finally 1, it'll be able to look up the other values in the different environments and add them up. It does this naturally, well, the code does this naturally, so that we do not have to do this - result += a, over and over again. Although, it's basically the same idea.

So there you have it. The recursive function is much cleaner! :)

Disclaimer: I am writing this at 2.06am, and I am not planning to test this code before publishing, so please feel free to comment and correct any error in my code and/or explanation. :)
My name is Martha Chumo (Njeri Chelimo). I am a self taught Web developer.

I am passionate about self learning! Anyone who has met me knows this about me. I believe that self learning is the purest form of learning. No pressure. You chose what to learn, when to learn it, how to learn it, and most importantly, you become a master of what you are learning. It allows you to go to extents you would have never imagined!

Just to be clear, self learning does not mean that you do not have a teacher, it simply means the teacher does not dictate what/how you learning. The teacher simply teaches, and you learn. In this age, self learning is pretty easy - with MOOCs and books available everywhere! I spend a lot of time learning, so I thought it is time I start documenting it. I feel there is a lot I would have loved to share, especially when I was starting out, but hey, important thing is that I am starting to document, finally!

I will update this blog everyday, starting today, with a summary of what I have learnt and hopefully, I will inspire the world to learn and grow! :)