Sep 28, 2010

Clojure Basics

Run clojure.jar by,
java -jar clojure.jar
and it will prompt,
Clojure got three main numerical types. Integr, Float and Ratio.
To do 1 + 2 it is; (+ 1 2)
If you need to defind a function you can defid as,
The function you need to defind is a = 2 + 3
So you can write it as,
user=> (def a(+ 2 3))
Then it will give an output as
and prompt user=>
If you type "a" in that you will get the output of 2+3 as 5.

Number formats
user=> 10 decimal 10
010 octal 8
0xff hex 255
1.0e-2 double 0.01
1.0e2 double 100.0

And also clojure supports a radix based entry format, in a form of (radix)r(number)
(note : 1(Integer/toString 10)
user =>(Integer/toBinaryString 10)

String to Integer
user=>(Integer/parseInt "B" 16)
user=>(Integer/parseInt "10" 16) ; 16r10
user=>(Integer/parseInt "101" 8) ; 8r101
User =>(Integer/parseInt "10101" 2)

Data Structures
Creating a stucture;
(defstruct employee :name :id)
Using the structures
(struct employee "Mr. X" 10)
We can make functions from these things and get values from them like;
(def e1(struct employee "Nimal" 324))
And if you type e1 it will give an output like
{:name "Nimal", :id 324}
Also you can get only a value you need by typing like;
(e1 :name)
This will print the name of e1.

We can use accessor function to get easy access of feilds. It is like this.
(def emp-name(accessor employee :name))
Now if you want to get the employee name of e1 you cann type as;
(emp-name e1)

Add or remove new fields to structures
We can only remove fields which are added by assoc, can't delete the fields which are defined by defstruct.
(def e1-new (assoc e1 :function "engineer"))
It will give the output as;
{:name "Nimal", :id 324, :function "engineer"}
(def e1-rm (dissoc e1-new :function))

No comments:

Post a Comment

Your comments are always welcome ...