Friday, August 19, 2011

Visualize Google search results with Clojure

One question that I always get asked when I introduce Clojure to my programmer friends is about its strength. While there are so much about Clojure that a programmer can benefit from, I always tend to single out one thing about it - powerful sequence processing. It shines when you are faced with solving any problem related to data processing. Rather than just talking how great it is to manipulate and analyze data, I actually created a project that I called gcount that shows Google search results in a bar chart. Here is the source: You can just clone it like this: git clone https://oneness@github.com/oneness/gcount.git Then you can run lein deps in gcount directory to pull all dependencies. When it is done, just evaluate core.clj file from the REPL and run: gcount.core> (search-view-terms ["Functional programming" "Object oriented programming" "Functional Object oriented programming"]) You will see following chart:
Next time when you need to show your friend how popular a particular term is, just show him/her this chart. Then you will have curious questions about how it is done and more about Clojure. Enjoy!

Friday, June 17, 2011

Simply the best* way to learn and hack Clojure

My previous blog created little bit controversy about the term "serious Programmers" that I have used in the title. So I am putting * after the term "best" to indicate that it is my personal opinion and readers can define their best way of doing the same.
Most of Clojure hackers agree that starting with Clojure can be frustrating. This has been discussed in google groups and elsewhere. Almost all hackers agree that
Clojure programmers spend most of their time in the REPL.
I find many different opinion about how to simplify this process. There are people
just complain about how hard it is while there are people outright defy and
provide all sorts of differing approaches, which adds to a newbie's confusion.
I actually created a project called ClojureW to help newbie get started easily and
quickly just to get a taste of Clojure (I blogged about where and how to get it in
my earlier blogs). This post is about a nice trick that I found to help with Clojure
hacking. In your .emacs file just put following:
(defun eshell-execute-selection ()
  "Insert text of current selection or clipboard in eshell and execute."
  (interactive)
  (require 'eshell)
  (let ((command (or (buffer-substring (mark) (point))
         x-last-selected-text-clipboard)))
    (let ((buf (current-buffer)))
      (unless (get-buffer eshell-buffer-name)
        (eshell))
      (display-buffer eshell-buffer-name t)
      (switch-to-buffer-other-window eshell-buffer-name)
      (end-of-buffer)
      (eshell-kill-input)
      (insert command)
      (eshell-send-input)
      (end-of-buffer)
      (switch-to-buffer-other-window buf))))

and map it to a shortcut key of your choice like this:
(global-set-key [f10] 'eshell-execute-selection)

Then start a Clojure REPL in eshell and type anything in a scratch buffer. You can
select any text and hit F10 to evaluate. One excellent side effect of this hack is
that you do not need to mess with SLIME or any other language specific set up. It
works with any command line tools you already familiar with. You can execute shell
scripts, Ruby scripts, and GNU Smalltalk scripts. If you have any frequently used
commands, it will be perfect to keep them in a file and just select and hit F10.

I found this approach very helpful when I need to experiment with Clojure or Java
libs or platforms such as Java Packages and Incanter(In case, if you are not heard
it is a R like statistical charting platform written in Clojure).

I hope someone finds this useful and Please share if you have handy hacks that ease the pain of hacking. Enjoy!

Disclaimer: I did not write the whole elisp code. I just modified it to work with any selection or clipboard content. I believe I found this elisp snippet somewhere in Emacswiki, a fantastic place to "steal" snippets to hack with.

Thursday, June 9, 2011

Two best programming languages for serious programmers

After working with Java for five years, I thought I knew about OO until I started learning about Smalltalk. Reading "Smalltalk by Example" - a free book that you can download from here - had profound impact on how I think about Object Oriented Programming. Java's procedural and OO mix left me in a half-way schizophrenic state. Despite having read and practice "Clean Code" by Uncle Bob, I still found many if/else, check result and poorly designed classes. The idea that everything I mean literally everything is an Object teaches you the foundation of OO: Message Passing. The only way of getting things done in Smalltalk is via message passing, which supports "Don't ask, tell" and "Put off as much as you can" golden rule. This way of thinking results in very elegant design and code.

Now you might wonder what are the two best programming languages I am talking about? You should know by now that the first one is Smalltalk. The second one is Clojure. Clojure cures the disease of writing hundreds of classes to deal with hundreds of different composite data structures. Why? Because you can't. The power of Clojure's sequence abstraction and provided core functions that operates on them gives you superman powers to manipulate data. For example, following simple function will condense strings by removing extra white spaces:
(ns compact
  "compact a string by removing extra white spaces")

(defn compact [s]
  (reduce #(str %1 " " %2)
   (filter #(seq %) (seq (.split s " ")))))

Usage:
(compact "  Your     uncompact    String  ")
-> "Your uncompact String"

I am not even contemplating the Java implementation of this simple function. This is all good. Why do I mention Smalltalk as the first one, you wonder. Here is why:
You do not need to implement the compact function. You just tell the String Object to compact itself. Here you go:
'  Your     uncompact    String  ' withBlanksCondensed
-> 'Your uncompact String'

You just send the "withBlanksCondensed" message and you are done. Clojure gives you the option of being practically lazy, but Smalltalk makes you one. So learn yourself a little Smalltalk and Clojure if you are really serious about programming with elegance and laziness.

Wednesday, January 19, 2011

Detect your host IP with Clojure

Recently I was faced with trivial task of detecting a host's IP address where the host could have multiple network interfaces. Based on how the local network was configured, you might have a luck with just a one liner in Clojure:

(import (java.net InetAddress))
(println (InetAddress/getLocalHost))

This will produce following:
;;user=> (import (java.net InetAddress))
;;(println (InetAddress/getLocalHost))
;;user=>
;;inet4address kpad/127.0.0.1
;;nil

Obviosly, that is not what you might be looking for since it is just a loopback address.
To find the your host LAN IP address, you need to find the not loopback interface and obtain the IP that is bound to it. It turns out it is pretty easy in Clojure. Here is whole thing:
===================================================================
import (java.net NetworkInterface))
(def ip
     (let [ifc (NetworkInterface/getNetworkInterfaces)
    ifsq (enumeration-seq ifc)
    ifmp (map #(bean %) ifsq)
    ipsq (filter #(false? (% :loopback)) ifmp)
    ipa (map :interfaceAddresses ipsq)
    ipaf (nth ipa 0)
    ipafs (.split (str ipaf) " " )
    ips (first (nnext ipafs))]
       (str (second (.split ips "/")))))
 

========================================================================

This will produce following:
;;user=> (println ip)
;;192.168.1.70
;;nil

Note: I am still learning Clojure and surely there will be better way of doing this. If you happen to know, please share. Thanks for reading.

Sociable