clojure

Reading Java properties file in Clojure

A simple and effective way to read properties files in Clojure, since they transform into Clojure maps!

(into {} (doto (java.util.Properties.)
         (.load (-> (Thread/currentThread)
         (.getContextClassLoader)
         (.getResourceAsStream "log4j.properties")))))

Next, to actually read this in, using atoms to swap the values like this seems to work,

(def *args*
  (atom {:a 10, :b 20}))

(defn -main []
  (swap! *args* assoc :a (read) :b (read)))

Mutable vs Immutable datastructures - Serialization vs Performance

In my last post, I was playing around with methods to serialize Clojure data structures, especially a complex record that contains a number of other records and refs. Chas Emerick and others mentioned in the comments there, that putting a ref inside a record is probably a bad idea - and I agree in principle. But this brings me to a dilemma.

Lets assume I have a complex record that contains a number of "sub" records that need to be modified during a program's execution time. One scenario this could happen in is a record called "Table", that contains a "Row" which is updated (Think database tables and rows). Now this can be implemented in two ways,

  • Mutable data structures - In this case, I would put each row inside a table as a ref, and when the need to update happens, just fine the row ID and use a dosync - alter to do any modifications needed.
    • The advantage is that all data is being written to in place, and would be rather efficient.
    • The disadvantage however, is that when serializing such a record full of refs, I would have to build a function that would traverse the entire data structure and then serialize each ref by dereferencing it and then writing to a file. Similarly, I'd have to reconstruct the data structure when de-serializing from a file.

 
{:filename "tab1name",
 :tuples
 #<Ref@511d89f8:
   #{{:recordid nil,
      :tupdesc
      {:x
       #<Ref@59a683e6:
         [{:type "int", :field "colid"}
          {:type "string", :field "name"}]>},
      :tup #<Ref@411a9435: {:colid 1, :name "akriti"}>}
     {:recordid nil,
      :tupdesc
      {:x
       #<Ref@59a683e6:
         [{:type "int", :field "colid"}
          {:type "string", :field "name"}]>},
      :tup #<Ref@424f8ad5: {:colid 2, :name "viksit"}>}}>,
 :tupledesc
 {:x
  #<Ref@59a683e6:
    [{:type "int", :field "colid"} {:type "string", :field "name"}]>}}

       

  • Immutable data structures - This case involves putting a ref around the entire table data structure, implying that all data within the table would remain immutable. In order to update any row within the table, any function would return a new copy of the table data structure with the only change being the modification. This could then overwrite the existing in-memory data structure, and then be propagated to the disk as and when changes are committed.
    • The advantage here is that having just one ref makes it very simple to serialize - simply de-ref the table, and then write the entire thing to a binary file.
    • The disadvantage here is that each row change would make it necessary to return a new "table", and writing just the "diff" of the data to disk would be hard to do.

 
#<Ref@4a3e7799:
  {:filename "tab1name",
   :tuples
   #{{:recordid nil,
      :tupdesc
      {:x
       [{:type "int", :field "colid"}
        {:type "string", :field "name"}]},
      :tup {:colid 1, :name "viksit"}}
     {:recordid nil,
      :tupdesc
      {:x
       [{:type "int", :field "colid"}
        {:type "string", :field "name"}]},
      :tup {:colid 1, :name "akriti"}}},
   :tupledesc
   {:x
    [{:type "int", :field "colid"} {:type "string", :field "name"}]}}

       

So at this point, which method would you recommend?

Serializing Clojure Datastructures

I've been trying to figure out how best to serialize data structures in Clojure, and discovered a couple of methods to do so. (Main reference thanks to a thread on the Clojure Google Group here )

(def box {:a 1 :b 2})

(defn serialize [o filename]
  (with-open [outp (-> (File. filename) java.io.FileOutputStream. java.io.ObjectOutputStream.)]
    (.writeObject outp o)))

(defn deserialize [filename]
  (with-open [inp (-> (File. filename) java.io.FileInputStream. java.io.ObjectInputStream.)]
    (.readObject inp)))

(serialize box "/tmp/ob1.dat")
(deserialize "/tmp/ob1.dat")

This works well for any Clojure data structure that is serializable. However, my objective is slightly more intricate - I'd like to serialize records that are actually refs. I see a few options for this,

- Either use a method that puts a record into a ref, rather than a ref into a record and then use the serializable, top level map
- Write my own serializer to print this to a file using clojure+read
- Use Java serialization functions directly.

Thoughts?

Stack implementation in Clojure II - A functional approach

My last post on the topic was creating a stack implementation using Clojure protocols and records - except, it used atoms internally and wasn't inherently "functional".

Here's my take on a new implementation that builds on the existing protocol and internally, always returns a new stack keeping the original one unmodified. Comments welcome!

(ns viksit-stack
  (:refer-clojure :exclude [pop]))

(defprotocol PStack
  "A stack protocol"
  (push [this val] "Push element in")
  (pop [this] "Pop element from stack")
  (top [this] "Get top element from stack"))

; A functional stack record that uses immutable semantics
; It returns a copy of the datastructure while ensuring the original
; is not affected.
(defrecord FStack [coll]
  PStack
  (push [_ val]
        "Return the stack with the new element inserted"
        (FStack. (conj coll val)))
  (pop [_]
       "Return the stack without the top element"
         (FStack. (rest coll)))
  (top [_]
       "Return the top value of the stack"
       (first coll)))

; The funtional stack can be used in conjunction with a ref or atom

viksit-stack> (def s2 (atom (FStack. '())))
#'viksit-stack/s2
viksit-stack> s2
#<Atom@69af0fcf: #:viksit-stack.FStack{:coll ()}>
viksit-stack> (swap! s2 push 10)
#:viksit-stack.FStack{:coll (10)}
viksit-stack> (swap! s2 push 20)
#:viksit-stack.FStack{:coll (20 10)}
viksit-stack> (swap! s2 pop)
#:viksit-stack.FStack{:coll (10)}
viksit-stack> (top @s2)
10

Stack implementation in Clojure using Protocols and Records

I was trying to experiment with Clojure Protocols and Records recently, and came up with a toy example to clarify my understanding of their usage in the context of developing a simple Stack Abstract Data Type.

For an excellent tutorial on utilizing protocols and records in Clojure btw - check out Kotka.de - Memoize done right .

;; Stack example abstract data type using Clojure protocols and records
;; viksit at gmail dot com
;; 2010

(ns viksit.stack
  (:refer-clojure :exclude [pop]))

(defprotocol PStack
  "A stack protocol"
  (push [this val] "Push element into the stack")
  (pop [this] "Pop element from stack")
  (top [this] "Get top element from stack"))

(defrecord Stack [coll]
  PStack
  (push [_ val]
        (swap! coll conj val))
  (pop [_]
       (let [ret (first @coll)]
         (swap! coll rest)
         ret))
  (top [_]
       (first @coll)))

;; Testing
stack> (def s (Stack. (atom '())))
#'stack/s
stack> (push s 10)
(10)
stack> (push s 20)
(20 10)
stack> (top s)
20
stack> s
#:stack.Stack{:coll #<Atom@d2c9015: (20 10)>}
stack> (pop s)
20

More tutorial links on Protocols,

[1] http://blog.higher-order.net/2010/05/05/circuitbreaker-clojure-1-2/
[2] http://freegeek.in/blog/2010/05/clojure-protocols-datatypes-a-sneak-peek/
[3] http://groups.google.com/group/clojure/browse_thread/thread/b8620db0b742...

Thrush Operators in Clojure (->, ->>)

I was experimenting with some sequences today, and ran into a stumbling block: Using immutable data structures, how do you execute multiple transformations in series on an object, and return the final value?

For instance, consider a sequence of numbers,

user> (range 90 100)
(90 91 92 93 94 95 96 97 98 99)

How do you transform them such that you increment each number by 1, and then get their text representation,

"[\\]^_`abcd"

Imperatively speaking, you would run a loop on each word, and transform the sequence data structure in place, and the last operation would achieve the desired result. Something like,

>>> s = ""
>>> a = [i for i in range(90,100)]
>>> a
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

>>> for i in range(0,len(a)):
...   s += chr(a[i]+1)
...
>>> s
'[\\]^_`abcd'

If you knew about maps in python, this could be achieved with something like,

>>> ''.join([chr(i+1) for i in range(90,100)])
'[\\]^_`abcd'

The easiest way to do this in Clojure is using the excellently named Thrush operator (-> and ->>). According the doc,

Threads the expr through the forms. Inserts x as the
second item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
second item in second form, etc.

It is used like this,

user> (->> (range 90 100) (map inc) (map char) (apply str))
"[\\]^_`abcd"

Basically, the line, (-> 7 (- 3) (- 6)) implies that 7 be substituted as the first argument to -, to become (- 7 3). This result is then substituted as the first argument to the second -, to get (- 4 6), which returns -2.

user> (-> 7 (- 3) (- 6))
-2

Voila!

Implementing Binary Search with Clojure

I was trying to implement a simple binary search using a purely functional approach, and after much hacking, googling and wikibooking, came up with this in Clojure.

(defn binarysearch
  ( [lst n]
      (binarysearch lst 0 (dec (count lst)) n))
  ( [lst lb ub n]
      (if (> lb ub) -1 ; this is the case where no element is found
          (let [mid (quot (+ lb ub) 2)
                mth (nth lst mid)]
            (cond
             ; mid > n, so search lower
             (> mth n) (recur lst lb (dec mid) n)
             ; mid < n, search upper
             (< mth n) (recur lst (inc mid) ub n)

Clojure Application with Command Line Arguments

I was recently looking for a method to create an application with Clojure that would allow specification of command line arguments.

I came across an excellent post on Stack Overflow by alanlcode , that provides a spectacular example. I've Github'd it for reference.

20 Days of Clojure

Came across an excellent series of blog posts by Lou Franco, where he uses the SICP videos as input to learn more about Clojure. His explanation of HashMap implementations in Clojure, using multimethods, as well as pointers on parallelizing functional programs are very well written. I'm currently on his day 10 post.

Programming Clojure with Clojure 1.2.0 snapshot

This post contains a list of changes between Clojure 1.1.0 and 1.2.0 that would affect you if you're reading Stuart Halloway's "Programming Clojure".

It looks like you'd have to replace,

(use '[clojure.contrib.str-utils :only (re-split)])
(filter indexable-word? (re-split #"\W+" "A fine day it is"))

with

(use '[clojure.contrib.string :only (split)])
(filter indexable-word? (split #"\W+" "A fine day it is"))

--> ("fine" "day")

since the str-utils module got renamed to string, and the re-split function to split.

Syndicate content