My thoughts on tackling IT complexity by breaking it into atomic components. and I term it lego oriented solution, LOS for short.
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:
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.
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:
Usage:
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:
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.
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:
===================================================================
========================================================================
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.
(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.
Friday, July 9, 2010
Flatten a directory with a filter in Clojure
I always wanted cross platform and stand-alone script to flatten a directory with an optional filter. I have relied on Ant builder from Groovy but it is slow and one needs to have Groovy installed along with Ant. So, I wrote a small script in Clojure that I can use and share with friends easily. Without further ado, here is the entire script:
Here is the source file for you to use, experiment or do whatever you want to have fun with Clojure.
Here is the source file for you to use, experiment or do whatever you want to have fun with Clojure.
Saturday, June 19, 2010
Ubiquitous note taking with Vim and Dropbox
Finally I found the combination of a best data sync tool called Dropbox and my favorite text editor Vim for ubiquitous note taking. To make it even seamless, I added following to my .vimrc and sharing it with you guys:
map <leader>nn :tabedit ~/Dropbox/YourName/notes/
<leader> here is a mapleader, which is a special variable in vim that you can bind to a key in your vimrc. I use following to map it to ","
let mapleader = ","
After that you can use comma with the combination of any characters for mapping things that you end up doing a lot. In this case, I mapped it to creating a new file in a new tab within ~/Dropbox/YourName/notes/ folder with whatever name that I will type before hitting the enter key. Above setting will allow following work flow:
1. Open vim
2. Just type ,nn and enter the file name you want
3. Hit enter and start typing
Creating a new notes could not be more easier and pleasant than this knowing that your notes will be automatically synchronized across multiple computers even on mobile phones. Enjoy!
map
<leader> here is a mapleader, which is a special variable in vim that you can bind to a key in your vimrc. I use following to map it to ","
let mapleader = ","
After that you can use comma with the combination of any characters for mapping things that you end up doing a lot. In this case, I mapped it to creating a new file in a new tab within ~/Dropbox/YourName/notes/ folder with whatever name that I will type before hitting the enter key. Above setting will allow following work flow:
1. Open vim
2. Just type ,nn and enter the file name you want
3. Hit enter and start typing
Creating a new notes could not be more easier and pleasant than this knowing that your notes will be automatically synchronized across multiple computers even on mobile phones. Enjoy!
Thursday, June 10, 2010
On learning idiomatic Clojure
If you hang around in Clojure google groups and Clojure user groups, one topic that keep popping up is this: How one go about learning idiomatic way of writing Clojure code? After reading almost every source that I could get my hands on, I finally settled for this:
(def
my-assoc
(fn my-assoc
([map key val] (assoc map key val))
([map key val & kvs]
(let [ret (my-assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret)))))
(println (my-assoc {} :symbol "assoc")) => {:symbo assoc}
my-assoc here is a Var that holds a reference to a function that named my-assoc, which takes a map and one or more key-val pairs, and returns a map that contains the mapping. This actually is a classic Clojure style of tail recursive function. Namely, it is an idiomatic way to use function signatures for base and recursive cases. It is also very elegant to use let binding to hold accumulative value that will be referred in multiple places in a block. The use of recur in the tail position is just what it is intended for. It recursively invokes my-assoc function with the correct number of arguments, which in this case
(my-assoc [map key val & kvs]) until kvs are nil, which is one of only two false (nil and false) in idiomatic Clojure. (first kvs) (second kvs) (nnext kvs) is also idiomatic way of traversing a seq that will save you from unexpected nil punning. (Again, read "Joy of Clojure" for detailed explanation for this).
My way of learning idiomatic Clojure is very opinionated and might not work for everyone. What is your way of learning idiomatic Clojure? Please share it if you can so a Clojure noob will have a good start.
- Study Clojure.core daily
- Read "Joy of Clojure" The Joy of Clojure
- Code, Code, and Code in Clojure as much as you can
(def
my-assoc
(fn my-assoc
([map key val] (assoc map key val))
([map key val & kvs]
(let [ret (my-assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (nnext kvs))
ret)))))
(println (my-assoc {} :symbol "assoc")) => {:symbo assoc}
my-assoc here is a Var that holds a reference to a function that named my-assoc, which takes a map and one or more key-val pairs, and returns a map that contains the mapping. This actually is a classic Clojure style of tail recursive function. Namely, it is an idiomatic way to use function signatures for base and recursive cases. It is also very elegant to use let binding to hold accumulative value that will be referred in multiple places in a block. The use of recur in the tail position is just what it is intended for. It recursively invokes my-assoc function with the correct number of arguments, which in this case
(my-assoc [map key val & kvs]) until kvs are nil, which is one of only two false (nil and false) in idiomatic Clojure. (first kvs) (second kvs) (nnext kvs) is also idiomatic way of traversing a seq that will save you from unexpected nil punning. (Again, read "Joy of Clojure" for detailed explanation for this).
My way of learning idiomatic Clojure is very opinionated and might not work for everyone. What is your way of learning idiomatic Clojure? Please share it if you can so a Clojure noob will have a good start.
Subscribe to:
Posts (Atom)