Sunday, February 3, 2013

Use lein 2 with swank clojure

If you are Clojure dev and not really ready to make the jump to nrepl but got to use lein 2.0, here is what you can do to save yourself some trouble. Lein 2 supports user profiles and you can add following to ~/.lein/profiles.clj:

{:user {:plugins [[lein-swank "1.4.5"]
                  [lein-pprint "1.1.1"]]}}

You can take out pprint but it is nice to have if you want to pretty print some data from your repl. 

Then you can cd to the directory where you have project.clj and simply run:
  • lein swank
  • slime-connect (from within emacs)
Now, enjoy all the goodies of lein 2 and stay with your good old friend slime. 

Friday, September 21, 2012

First month @Runa Inc. - Clojure shop in Silicon Valley

Recently, about a month ago to be precise, I was fortunate to join one of the Clojure powerhouse in the Bay Area, Runa Inc. I have to say that what I saw within first month of my real Clojure shop experience is so great that I made a personal commitment to write about at least one Clojure blog post a month about my journey there.
First of all, the choice of Clojure for the types of problems Runa is set out to solve is beyond the doubt is the right one. For any data centric projects, Clojure seems to be the best suited language out there for now. However, the aim of my post is not to convince what has already been pretty well known about Clojure. Rather, I would like to share few things about Runa's Clojure projects. Since I started with Runa, I found following about a project that I was assigned to work:
  • TDD is done right.  As stated in Amit's excellent book, Clojure in action, Runa really does stick with and encourage developer to use TDD. The project is very well tested and working with it has been a joy so far. In case if you have not read the book yet, the usual TDD flow is: Write failing test -> Make it pass -> Refactor and repeat. For example, if you are testing for existence of a particular information in a log file, which in turn comes from some configuration file, here is how you would put TDD in practice (Will post concrete examples in my next blog post): 
             - Write a failing test to check for the missing information that is not there.
             - Put the information in the config file and make the test pass
             - Refactor such as separate out config file creation and deletion using high order function. 
  • Small core.  What I am very excited about the project is that there is no frameworks or huge external library dependencies in it. It has minimal external libraries and has a very small and well tested core. Usage of fast and small library is always preferred to keep its foot print small. This has also added benefit of much portability in terms of deployment and being used as a module for other projects. The project is a high performance web service and it does not even use ring or compojure. It just uses jetty library.
  • Clojure can be fast, I mean really fast.   There are many ways to speed up clojure projects such as type hinting, using memoziation and using performant data structures such as chuncked sequence. But there are cases that one can utilize plain old java to speed it up even more. The project has very strict response time (a request response time has to be under 3 millisecond). Since we are all stateless, we end up using number of single java thread processes for logging, monitoring,instrumentation and also java queues from java.util.concurrent package. Now we are able to serve 40 thousand requests per second under 15% load capacity of per app instance.(The app is deployed on over a dozen nodes with a load balancer routing requests). I will blog with more details such as performance charts and overall big picture design in my future blog posts. 
If above sounds interesting to you, check us out.

Saturday, February 25, 2012

Simple way to use Clojure in Emacs 24

I have been thinking of writing this up for sometime. Do we really need another post about how to get started with Clojure in Emacs? There are so many articles on plethora of ways of doing this on the inter web. Honestly speaking, I have tried them all. I am not gonna list them here to save myself and you the trouble of being distracted. Finally, I have settled with following and I hope you do the same.
1. Install leiningen:
  a. wget https://raw.github.com/technomancy/leiningen/stable/bin/lein
  b. chmod +x lein
  c. lein self-install
  Note: If you are lucky user of Ubuntu 11.10, do: sudo apt-get install leiningen
2. Intall Emacs 24
  Ubuntu: sudo apt-add-repository ppa:cassou/emacs; apt-get install emacs-snapshot
  Mac OS: get it here: <a href="http://emacsformacosx.com/"></a>
3. Put following lines in your .emacs file and restart your emacs
(require 'package)
(add-to-list '
package-archives
             '("marmalade" . "http://marmalade-repo.org/packages/"))
(package-initialize)
(add-hook '
clojure-mode-hook
          (lambda ()
            (setq inferior-lisp-program "lein repl")))

Once your Emacs starts up fine, issues following command to get clojure mode:
Alt-x package-install clojure-mode

Then you can just open a clj file and run: alt-x inferior-lisp. You will get yourself a nice repl within Emacs and start hacking. Following is a quick summary of what you can do:
1. Move around defn and def forms with Ctrl-Alt-p and Ctr-Alt-n for up and down
2. Evaluate defn and def with Ctrl-Alt-x while the curser is anywhere within the form
3. Use Alt-p and Alt-n to navigate repl history

Plus, enjoy all of the rest of Emacs' superb editing powers while you are at it. I am also thinking of starting conversational style Clojure programming guide and let me know if you are interested in proof reading or contributing.

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.