Showing posts with label clojure. Show all posts
Showing posts with label clojure. Show all posts

Friday, April 2, 2010

Emacs, Clojure, and Windows 7

Okay, I had to wrestle with this. Maybe that makes me dumb, but if you're reading this, then you ain't doin' much better. I've had an on-and-off again, love/hate relationship with emacs over the years, and I'm swinging back to "on/love" while dinking around with Clojure. Emacs really is the best Lisp-type environment, even on Windows.

To give credit where due, I started with this good post on freegeek.in, but some bits were outdated.

Pre-requisites

First, get emacs installed. Find the latest version in this folder, and extract it someplace - no installation is really necessary.

You also need git. Let's assume you get through all of that.

Last, but not least, you should have a JDK installed.

Add the path to git and java.exe to your PATH, and set JAVA_HOME to your JDK. If you don't want to do that, then start a command prompt, set them manually, and do anything emacs-y from there.
set PATH=%PATH%;c:\sys\git\bin;c:\sys\emacs-23.1\bin
set JAVA_HOME=c:\program files\Java\jdk1.6.0_19
runemacs

Emacs Starter Kit

Next, install the Emacs Starter Kit. This is a huge time-saver. Many of my previous complaints about emacs tended to be having to learn so much just to modify the environment. This takes care of a majority of that. One of the nice, and really important bits is ELPA - a package management system for emacs. In one fell swoop, 80% of my complaints have been silenced.

Anyway, download the ESK from github

git clone git://github.com/eschulte/emacs-starter-kit.git C:\Users\<userdirectory>\AppData\Roaming\.emacs.d

If you have a C:\Users\<userdirectory>\AppData\Roaming\.emacs file, rename it. You can copy it to custom.el, and it will be used as normal. Most of the action occurs in init.el, so that's a good place to look if you really don't like something.

Nope, we're not quite there yet. Before you can use it, you need to install org-mode.

cd C:\Users\<userdirectory>\AppData\Roaming\.emacs.d
git submodule init
git submodule update


Fire up emacs, and M-x package-list-packages. Scroll right on by that tempting "clojure-mode", and put your cursor on "swank-clojure", then press "i" (to select it for installation), then "x" (to start the installation).


Okay, here's where I ran into a problem: when trying to use ELPA, I got the following error: "Local variables entry is missing the suffix". The nice thing about obscure error messages is that they are usually pretty easy to search on. (There's a patch here, only the file name is "package.el"

You'll be adding a function, and modifying package-unpack-singe to use it.

(defun package-write-file-no-coding (file-name excl) 
 (setq buffer-file-coding-system 'no-conversion) 
 (write-region (point-min) (point-max) file-name nil nil nil excl))

The ESK instructions say to build org-mode after that, but launching emacs seemed to take care of that.

Using it

Woooo! Installed! Isn't this easier than NetBeans? (well, actually "yes" for me, since it was some frustration with Enclojure that drove me back to emacs)

Launch emacs, and type M-x slime. If you have everything set up right, you should be prompted to install clojure. This will not only install clojure, but also get you the swank-clojure.jar you'll be needing for projects.

Projects

Assuming you got your SLIME prompt in the step before, creating a project is easy, but not as easy as it could be.

Create the following directory structure wherever it is you want your project to go:

root
  +--src
  +--lib
  +--classes
In the lib directory, put your clojure, clojure-contrib, and swank-clojure jars. You can find them in C:\Users\<username>\AppData\Roaming\.swank-clojure Then you should be able to start a new project with:

M-x swank-clojure-project

That should do it - hope it helps

Tuesday, October 27, 2009

Eclipse and Clojure Unit Testing

So far, I'm enjoying my little Clojure projects. The biggest weakness is the IDE, NetBeans, specifically. I haven't and probably won't bother with the emacs version. I'm sure there's things about it that work better, but I'm way too spoiled.

To be fair, the NetBeans plugin is in alpha state. It should get better - this is just a snapshot at this point in time.

As I've worked on this intermediate app, I've had occasion to go back and modify some of the java code I'd already written. Given all the refactoring and testing handholding which NetBeans provides, making those changes was pretty easy.

Here's the world in which I'm living: To get unit tests even somewhat integrated, I call and organize them from main.

(ns some-ns.main
(:gen-class)
(:use
clojure.contrib.test-is))

(defn -main []
(run-tests
'some-ns.someclass
'some-ns.otherclass
))

Because of the IDE integration differences, I can't say that I'm more productive in Clojure. A huge difference is highlighting syntax errors. In Java, they pop up immediately and are easily dealt with. In Clojure, I have to compile before I find out I fat-fingered something.

Debugging is similar. No breakpoints and horrific stack-traces. A good chunk of my code is devoted to logging (which is good and all, but c'mon).

I'm sure things will improve over time. Like I said, the plug-in is alpha. If the language gains much momentum, I expect to see improvements. I have the feeling that it won't gain enough to compare to the ease of Java (I can't believe I just typed that) overall.

Overall, I'm enjoying the experience. I am accomplishing a lot, pretty quickly, and it seems like there is a lot less jumping around trying to keep all the different parts working together.

Friday, October 16, 2009

Beginning Clojure Macros - Part 2

Last time, we went over what macros were, and their parts. I also gave a pretty poor example of how to use them. I'll be taking that same code and being a little more efficient about it.

(defn parse-ip [ip current]
(if
;;; probably should use the network lib to be as accurate as possible...
;;; but I won't
(re-matches #"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" ip)
(inc-summary-counter current ip)
current))

(defn parse-datetime [ datetime current ]
(if
;;; since we're splitting on spaces, we get back "[19/Jan/2006:04:30:26"
(re-matches #"\[.{20}" datetime)
(inc-summary-counter current (subs datetime 1 12))
current))
There's a lot of repetition there. It's a simple if statement, but it will do for this example.


(defmacro parse-field [ valid-expr update-expr skip-expr ]
`(if
~valid-expr
~update-expr
~skip-expr))

Awesome! We just re-created if! Let's use it...


(let [[chash ctext] (get-field results :path-summary 6 nline)]
(parse-field
(re-matches #"/.+" ctext)
(inc-summary-counter chash ctext)
chash))

At least that's more self-explantory than a commented if-statement. Let's sort-of expand this.


(let [[chash ctext] (get-field results :path-summary 6 nline)]
;;; replacement of "parse-field" begins here
(if
;;; ~valid-expr
(re-matches #"/.+" ctext)
;;; ~update-expr
(inc-summary-counter chash ctext)
;;; ~skip-expr
chash))

Yep. That's it. Effectively, the only thing that changed was parse-field into if, right? Yes, but rather than evaluate the expressions, then pass them, we're passing the expressions themselves. They don't get evaluated for their values until they are required. Clojure already does things quite lazily, and caches a lot, but it can't anticipate everything, such as a long-running database call. It sometimes is just better to build in assurances yourself, anyway.

Why not a function?


Another way to achieve the same thing would've been to pass anonymous functions to another function. This would achieve the deferral of expensive evaluations, encapsulation, expressiveness, etc., as well, thanks to the power of closures:

(defn parse-field-fn [ current-hash current-text valid-fn update-fn ]
(if
(valid-fn current-text)
(update-fn current-hash current-text)
current-hash))

(let [[chash ctext] (get-field results :path-summary 6 nline)]
(parse-field-fn
chash
#(re-matches #"/.+" ctext )
#(inc-summary-counter chash ctext)))


When should I use macros instead of functions?


You should look for opportunities any time you're writing a function to replace structure. I only used a single if statement, but it could have had several. Another good opportunity is to replace a complicated function. If you have multiple nested if statements, conds, whatever, the main code can be easier to read by using a macro.

In all, though, learning macros - and any metaprogramming techniques - is worthwhile. It gives you greater control assembling the various bits and pieces which make up the program.

Beginning Clojure Macros - Part 1

I finally got around to learning the macro system in Clojure. When I'm picking up a new language, one of the first things I do is write an app which parses log files. I keep some around, just for that. There's a lot on the web about learning Clojure, but not as much about its macro system, not to mention macros, in general.

What's a macro?


According to this tutorial on which I've been leaning heavily:
Macros are used to add new constructs to the language. They are code that generates code at read-time.

To further oversimplify, macros are some really smart text substitution. Sort of.

You use macros to re-use code structure. You probably already do this with generic algorithms as part of your abstraction, but macros let you generate those algorithms dynamically. Applied appropriately, they result in cleaner code.

What is macro expansion?


When the compiler takes your source code, the first thing it does is look for macros. It "expands" the macro into the defmacro, replacing the text of one for the other.

Consider the text "The quick brown fox jumps over the lazy dog". There's a structure to that sentence, "The jumps over the lazy dog" (and more that we could abstract away, but we're keeping it simple here). If our macro is "", and we've defined it as "gazelle", then the resulting sentence would be "The gazelle jumps over the lazy dog".

Simple enough, right?

An actual code example



Log files have a bunch of different fields, and they all have their little peculiarities to deal with. To that end, I've got a couple of filter-ish functions: parse-ip and parse-datetime.

The two share a lot of similarities. They both check to see if the data is valid, and if it is, then update the current data and return the results, otherwise return the original results. Inside of the update, we update the map, either creating a new entry with a value of "1", or incrementing the existing entry.

I've added a bunch of comments to help explain the various pieces of a macro.

(defn parse-ip [ip current]
;;; accepts the IP address field as a string
;;; the current hashmap is updated and returned

;;; is it actually an ip address?
(if
;;; probably should use the network lib to be as accurate as possible...
;;; but I won't
(re-matches #"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" ip)

;;; increment the count
(assoc current ip
(if (contains? current ip)
(+ 1 (get current ip))
1 ))

;;; not an ip address
current))

(defn parse-datetime [ datetime current ]
(if
;;; since we're splitting on spaces, we get back "[19/Jan/2006:04:30:26"
(re-matches #"\[.{20}" datetime)

(let [ dt (subs datetime 1 12) ] ;;;(subs datetime 1 12)]

(assoc current dt
(if (contains? current dt)
(+ 1 (get current dt))
1 )))
current))


We'll take care of the hash update part, first, and replace that whole assoc form with something else.

;;; our macro takes two parameters, like a function
(defmacro inc-summary-counter [ hset nkey ]
;;; see the little "`" at the beginning?
;;; that means "don't evaluate anything, just return the text"
`(let
;;; there's two "weird" things in this let form
;;; the "#" after the first "hset"
;;; and the "~" before the second "hset"
;;;
;;; the suffix "#" means "generate a symbol for this",
;;; essentially a name which is guaranteed unique to this macro expansion
;;;
;;; the prefix "~" means "expand this passed variable"
;;; "~hset" will be replaced with the text of "hset"
;;;
;;; the reason for this particular little trick is to make sure that "hset"
;;; is evaluated only once, and it's result kept in a binding
[ hset# ~hset
nkey# ~nkey ]

;;; all of this will be returned as-is
(assoc hset# nkey#
(if (contains? hset# nkey#)
(+ 1 (get hset# nkey#))
1))))


Well, that was a lot to "save time", wasn't it? Here's our updated filter code, minus but using inc-summary-counter:

(defn parse-ip [ip current]
(if
;;; probably should use the network lib to be as accurate as possible...
;;; but I won't
(re-matches #"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" ip)
(inc-summary-counter current ip)
current))

(defn parse-datetime [ datetime current ]
(if
;;; since we're splitting on spaces, we get back "[19/Jan/2006:04:30:26"
(re-matches #"\[.{20}" datetime)
(inc-summary-counter current (subs datetime 1 12))
current))

Much prettier, wouldn't you say? Nothing you couldn't do with a function, but it is what is happening that is important.

Everywhere you see inc-summary-counter and parameters, that expression is replaced with it's defmacro.

Here's parse-ip again, with the macro pseudo-expanded.

(defn parse-ip [ip current]
(if
;;; probably should use the network lib to be as accurate as possible...
;;; but I won't
(re-matches #"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" ip)
;;; inc-summary-counter was here
(let
;;; the ~hset and ~nkey have been replaced
[ hset# current
nkey# ip ]
(assoc hset# nkey#
(if (contains? hset# nkey#)
(+ 1 (get hset# nkey#))
1))))
current))

Remember that macro-expansion happens before compilation? So, after the macros are expanded, the above code is what is passed to the compiler. I'll have a more powerful example next time.