Oct 6, 2010

Clojure Namespace

This is required to load clojure libraries, use to reffer curent namespaces and
to import java classes. We can use these pre defined source codes in our progrms. These are for commen need in most of programs.
Load a clojure library you can use,
(require 'clojure.contrib.math)
and to print all the loaded namespaces,
(all-ns)
If you need to load and reffer all at onec, you can use this command,
(use 'clojure.something.something)
And if you only need to reffer to a singl thing you can use
(use '[clojure.some.some :only (thingYouNeed)])

Importing Java libraries and classes

Think if you need to import java IO file in you clojure program you can do it by writing;
(import java.io.File)
If you need to import classes from a java package you can use;
(import [java.util Date Random])
This will import both Date and Random in util package.

Writing clojure programs

We can write a clojure program and store it in a seperate file and we can use it by calling that file. So to do that we can use java namespaces. If the namespace is like com.my-app.util, your clojure file should be placed in file structure
like com/my-app/util.clj. So we must begin the file with namespace as ;
(ns com.my-app.util)

So let's do a test program.
First create a folder called student in the directory where the clojure.jar placed. Then write this coding to a file called name.clj .
(ns student.name)
(defn my_name [sentence] (str "Welcome " sentence "...!"))

Now run the clojure.jar file and import this clojure file to the interpreter by;(use 'student.name)
Then try this;
(my_name "Thilina")
It will give the output as;
Welcome Thilina...!

2 comments:

  1. Note that a dash "-" in a namespace needs to be an underscore "_" in a pathname so your example for (ns com.my-app.util) should be saved in the path "com/my_app/util".

    ReplyDelete
  2. The "-" to "_" conversion is necessary because of of Java class naming. "-" isn't a valid part of a Java identifier (because Java regards it as an operator).

    This can be confirmed by using static methods of the Character class.

    user> (Character/isJavaIdentifierPart \_)
    true
    user> (Character/isJavaIdentifierPart \-)
    false

    ReplyDelete

Your comments are always welcome ...