Monday, April 26, 2010

let and binding macros in Clojure

Clojure has a special form called "let" and "binding", which are actually implemented as macros. It can get confusing sometimes.  If you have read "Programming Clojure" book, you might be thinking that it is easy to use them correctly considering following straightforward example:
Basically, "let" creates a lexical scoped Vars, which is local to the code block or a procedure where it is initially defined. Therefore, in the example above, "let" just created a new "x" with the value of "new value". But it is not local to the function "print-x".  That is to say, "print-x" have no knowledge of the local scoped binding that is created by "let". "binding" macro instead creates a new binding for the already existed var, "x" with the "new value". Since "print-x" is evaluated within the "binding" form, the newly bound value is visible to any chained calls within the form.  All nice and easy. However, it is not that obvious to understand and use them correctly. Look at following example:
"let" example is just fine. It created a new var "y" with the value of 5 bound to it.  But what is going on with the "binding" example? If we dig little deeper to Clojure API doc, we learn that the new bindings in "binding" are made in parallel, not sequential as it is in "let". Therefore, existing var "y" gets bound to the root binding of "x" not the overshadowed value of "x", which is the case in the "let example".
OK, so far so good. Let us look at another example:
Line 20-29 is pretty straight forward. But how about line 30? Shouldn't  it call "print-y" function? Not really. It is because the anonymous function is evaluated outside of the "binding" form.





To see this in action let us try following:



The "#<user$eval__28$fn__30 user$eval__28$fn__30@bdb503>" is an indication that anonymous function did not get evaluated within the "binding" form.  Ok, now, how do you make sure it evaluates within the "binding" form? Here is what you do:



Just enclose the anonymous function within parenthesis.  What do we learn from all of the above? Here are the summary that helps one use "let" and "binding" correctly:
  • Use "binding" only if you are trying to alter a behavior dynamically for special-vars that is already defined. Enclose your special vars within * as recommended by idiomatic clojure to make your intent clear.
  • Use "let" for locally scoped vars and avoid shadowing already defined vars.
  • Remember "let" binding is sequential and "binding" binding is done in parallel.
  • Pay close attention to the scope of the "binding" form. Any expression that is not evaluated inside the form, will not see the binding. That is to say, binding in "binding" form is thread local starting from the "binding" form until it ends including any expression that is chained within the form, which is what the thread-local are all about.
I posted this so that it helps someone trying to find his or her way in the wonderful world of Clojure.  

Thursday, April 22, 2010

Easy way to start with Clojure developement

For any software developer, I recommend learning functional programming, which is especially true for anyone who spent quite a bit of time on doing Object Oriented Programming.  As far as my experience from Ruby -> Groovy -> Scala -> Clojure journey concerned, I strongly recommend learning Clojure to get into functional way of thinking in practical way.  One of the hurdles that I encountered in getting started with Clojure is lack of a simple way of setting the environment. Yes, there are many ways one can get started such as Lein, Maven+Clojure Plugin, Emacs+Swank+Slime, Vim+VimClojure, Eclipse+CounterClockWise, NetBeans+Enclojure, IDEA+LaClojure, you name it. But it all makes a newbie to spend days if not hours to get his or her environment right.  After playing the hard way( Emac+Swank+Slime, Vim+VimClojure), which I do not recommend for a new comer,  I ended up creating a project called ClojureW.  It is the easiest way to start with Clojure as far as I know for all three major OSes such as Windows, OS X and Linux.  Here is all you need to get going:
1.       Download Clojurew from: http://bitbucket.org/kasim/clojurew/get/tip.zip
2.       Unzip it to a folder and change to bin directory of this folder
3.       Just run clj to get a REPL or run clj cljscript.clj to execute your script.

For beginners, I recommend just using a text editor that highlights matching parenthesis.  Believe me, trying to set up an “IDE” for Clojure is painful if not disappointing at best.  The main thing that you learn from Clojure is to think bottom-up when solving problems.  You can practice this approach with any language but Clojure will force you to think this way.  Again, setting up IDE is a hindrance to what Clojure is really about at the beginning. You can play with IDEs once you get into idiomatic Clojure way of thinking.  As stated by a book titled, “97 Things Every Programmer Should Know”, being able to quickly type up a simple “Hello World” program and run it via command line can prove extremely valuable after all.#  

Friday, February 26, 2010

Books everyone should read not just geeks or hackers

It has been a while since I did not write anything on my blog. I have been busy with work and reading among other things. But two books I read recently made me to want to blog about them. One is Paul Graham's Hackers and Painters, the other is Pomodoro Technique Illustrated by Staffan Noteberg.
On Hackers and Painters:
It is a great book especially for programmers. The breadth of common sense and not so common sense knowledge is breathtaking. It offers unique perspective on programming languages. It is pretty much biased towards Lisp, which is understandable considering his success and expertise on it. However, his advice of not learning Lisp for people over the age of 25 does not do justice to such a great language that every programmer should learn even if they do not use it. I am recent Lisp convert and I can already see its benefit to my daily work. I think earlier Lisp Dialects did not catch on because of its "strange" syntax, which made it more implementer friendly but not user friendly. But a recent dialect called Clojure is poised to make Lisp very very popular. Because the creator of Clojure is making very very nice middle road approach between user and implementer of the language. Anyway, Paul Graham's collection of essays in his book is really eye opening. There is chapter on how America's public school system works, why it is works the way it is and how adults should help kids between the age of 11 and 17. There is also a chapter about how to create wealth. His take on start ups are really thoughtful.

On Pomodoro Technique Illustrated:
Pomodoro means tomato in Italian. It is a focus training method that helps every goal oriented person by allowing them to get things done. What is unique about it is:
1. It is simple
2. It is easy
3. It is effective

Here is what you need to do:
1. Pick a to do item now
2. Set 25 minutes timer and start doing it now
3. Repeat above with new to do item if you finish or continue working after a short break.

All you need is a Timer, a sheet of paper, and your attention. In this memory overflow day and age, everyone needs to stay focused to get anything done. Countless interruption and stimulus is making people not even be able to concentrate for 25 minutes. Try it and you will be more productive.

Friday, January 8, 2010

To roman implementation in Clojure

Here is my take of to roman implementation in Clojure:
I posted this in http://rosettacode.org/wiki/Roman_Numerals#Clojure

1:  (def arabic-roman-map
2: {1 "I", 5 "V",
3: 10 "X", 50 "L",
4: 100 "C", 500 "D",
5: 1000 "M",
6: 4 "IV", 9 "IX",
7: 40 "XL", 90 "XC",
8: 400 "CD", 900 "CM" })
9: (def arabic-roman-map-sorted-keys
10: (sort (keys arabic-roman-map)))
11: (defn find-value-in-coll
12: [coll k]
13: (let [aval (find coll k)]
14: (if (nil? aval) "" (val aval))))
15: (defn to-roman
16: [result n]
17: (let
18: [closest-key-for-n (last (filter #(> n %) arabic-roman-map-sorted-keys))
19: roman-value-for-n (find-value-in-coll arabic-roman-map n)
20: roman-value-for-closet-to-n (find-value-in-coll arabic-roman-map
21: closest-key-for-n)]
22: (if (or (<= n 0) (contains? arabic-roman-map n))
23: (conj result roman-value-for-n)
24: (recur (conj result roman-value-for-closet-to-n)
25: (- n closest-key-for-n)))))
26: Usage: >(to-roman [] 1999)
27: result: ["M" "CM" "XC" "IX"]

Thursday, October 15, 2009

P12: Decode run-length encoding

Following is the direct solution:

1:  def decode(list:List[(Int,Any)]):List[Any] = {  
2: val b = new ListBuffer[Any]()
3: var temp = list
4: while(!temp.isEmpty){
5: for(i<- 1 to temp.head._1){
6: b+=temp.head._2 }
7: temp = temp.tail
8: }
9: b.toList
10: }
11: println("input List = "+dlist)
12: println(decode(dlist))

The input:
List((6,'a), (2,'c), (4,'e))
The output:
List('a, 'a, 'a, 'a, 'a, 'a, 'c, 'c, 'e, 'e, 'e, 'e)

P11: Modified run-length encoding that includes only repeated elements

Use unflatten method from P9 and filter it before mapping the sublist as a tuple:
println(ulist.filter(_.length > 1).map(e=>(e.length,e.head)))

Output:
List((6,'a), (2,'c), (4,'e))

Wednesday, October 14, 2009

Installing Eclipse, Scala and Groovy in Windows 7

There are many ways to install them on Windows 7. I am just listing following simple ways that worked for me:
1. Installing Eclipse 3.5
The latest 3.5 version works just fine on Windows 7. download it then unzip it to a location of your choice.
2. Installing Scala
Download IzPack installer, Just follow the wizard and you are done.
3. Installing Groovy
Download the Windows-Installer package. After installation, you need to do following:
1. Open Control Panel->System and Security->System and click on Advanced system settings.(Shortcut: Win+Pause/Break combination is your friend)
2. Click on Environment Variables
3. Make sure to create User variables such as GROOVY_HOME as name, installation location as value. (Note: Creating System variables did not work for me)
That is all there is to it. I hope someone find this post helpful.