Namespaces in Clojure: How to use the multitude of ns options

Namespaces in Clojure allow you to use various options, like :require, :use, etc. The syntax of those isn't as well documented as I'd like though in the API documentation.

Stack Overflow again comes to the rescue with some good answers, distinguishing between using :use versus :require.

The syntax is easily understood by an example, like so:

(ns example-namespace.core
  (:require [incanter
            [core :as i.c :only [col-names sel $ dim]]
             [io   :as i.io :only read-dataset]]
            [mmemail.core :as mail]
             [seq          :as c.c.seq :only positions]
             [except       :as c.c.except :only throwf]
             [json         :as c.c.json :only read-json]
             [command-line :as c.c.cmd :only with-command-line]]))

:use and :require has the same syntax, except the :as short-namespace-name is useless for :use since :use allows you access to the functions in that namespace without qualifying which namespace it's from.

The :only function-name and :only [fun1 fun2] parts says only the specified functions are being used in this namespace from the specified namespace.

The [package.name class1 class2] or alternatively [package.name [class1 :only fun1] [class2 :only fun2]] tells us which "classes" or specific namespaces are being used from the specified package of namespaces.

You need :gen-class if you want to one day compile and package your program for distribution as a Java jar.

There's a subtlety with having namespaces or packages with a dash in it as in example-namespace. See my previous post on namespaces for details.

No comments: