Sep 30, 2010

Exceptions and a simple program

Exception handling in clojure

Clojure supports java based exceptions. There are two types of exceptions in clojure. One is clojure exceptions and the other is user defined exceptions. If you type as;
user=>(/ 1 0)
This is devide 1 by 0. So this will give an exception.
So, this is the way to catch the exceptions.
user=>(try (/ 1 0 ) (catch Exception e (prn "Cach the exception" ))(finally (prn "In finally...")))

Now it will handle the exception. But if you use a wrong type of exception it will not catch that and in the end of the try statment it will give the error.

Writing a simple clojure program.
Now we will try to write a clojure program to add remove and change things.

(alias 'set 'clojure.set)
This wiil make an alias to clojure.set. Now we can use "set" word when ever we need to write clojure.set/smoething.

(defstruct employee :name :id :role)
This will create a structore named employee.
(def employee-records (ref #{}))
The "ref" is to allow mutation of a storage with transactions.

(defn- update-role [n r recs]
(let [rec (set/select #(= (:name %) n) recs)
others (set/select #(not (= (:name %) n)) recs)]
(set/union (map #(set [(assoc % :role r)]) rec) others)))
In this set of codes, "defn-" defineds a private function. As previously sed here we use set/select behalf of clojure.set/select.

(defn- delete-by-name [n recs]
(set/select #(not (= (:name %) n)) recs))
Both of these functions update and delete will do the operation and create a
new set of data, becouse these sequences are immutable.
Now you can see some public functions which will not cantaining a "-" sign when definding it.

(defn update-employee-role [n r]
"update the role for employee named n to the new role r"
(ref-set employee-records (update-role n r @employee-records))))

(defn delete-employee-by-name [n]
"delete employee with name n"
(ref-set employee-records
(delete-by-name n @employee-records))))

(defn add-employee [e]
"add new employee e to employee-records"
(dosync (commute employee-records conj e)))
Now the code is completed. Save this as test.clj and in the clojure prompt you
can import that coding by,

(load-file "test.clj")
Then you can do add delete and change employee details. Here is some
coding to add some data initially. Then after that you can view what you enered.(add-employee (struct employee "Jack" 0 :Engineer))
(add-employee (struct employee "Jill" 1 :Finance))
(add-employee (struct-map employee :name "Hill" :id 2 :role :Stand))

No comments:

Post a Comment

Your comments are always welcome ...