You're viewing version 1.2.0 of ns. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16
  • (ns name docstring? attr-map? references*)
Sets *ns* to the namespace named by name (unevaluated), creating it
if needed. references can be zero or more of: (:refer-clojure ...)
(:require ...) (:use ...) (:import ...) (:load ...) (:gen-class)
with the syntax of refer-clojure/require/use/import/load/gen-class
respectively, except the arguments are unevaluated and need not be
quoted. (:gen-class ...), when supplied, defaults to :name
corresponding to the ns name, :main true, :impl-ns same as ns, and
:init-impl-ns true. All options of gen-class are
supported. The :gen-class directive is ignored when not
compiling. If :gen-class is not supplied, when compiled only an
nsname__init.class will be generated. If :refer-clojure is not used, a
default (refer 'clojure) is used. Use of ns is preferred to
individual calls to in-ns/require/use/import:

(ns foo.bar
(:refer-clojure :exclude [ancestors printf])
(:require (clojure.contrib sql sql.tests))
(:use (my.lib this that))
(:import (java.util Date Timer Random)
(java.sql Connection Statement)))

9 Examples top

  • ;; Generate a Java class
    (ns org.clojuredocs.test
          (:gen-class))
    
    (defn -main [] (prn "Hello, World!"))
    
    
    ;; After compilation:
    sh$ java -cp classes org.clojuredocs.test
    Hello, World!
    
  • ;; Let's create a namespace and then assign it as the current namespace
    user=> (create-ns 'my-new-namespace)
    #<Namespace my-new-namespace>
    
    user=> (ns 'my-new-namespace)
    java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to clojure.lang.Symbol (NO_SOURCE_FILE:26)
    ;; oops, this is not the way to do it; if create-ns needs a symbol, ns does not
    
    user=> (ns my-new-namespace)
    nil
    
    my-new-namespace=>
    ;; it worked as the current namespace is our newly created one
    
    
  • ;; Generating a class so we can call Clojure from Java 
    (ns com.domain.tiny
      (:gen-class
        :name com.domain.tiny
        :methods [#^{:static true} [binomial [int int] double]]))
    
    (defn binomial
      "Calculate the binomial coefficient."
      [n k]
      (let [a (inc n)]
        (loop [b 1
               c 1]
          (if (> b k)
            c
            (recur (inc b) (* (/ (- a b) b) c))))))
    
    (defn -binomial
      "A Java-callable wrapper around the 'binomial' function."
      [n k]
      (binomial n k))
    
    (defn -main []
      (println (str "(binomial 5 3): " (binomial 5 3)))
      (println (str "(binomial 10042 111): " (binomial 10042 111))))
    
    
    ;; Calling from Java
    import com.domain.tiny;
    
    public class Main {
    
        public static void main(String[] args) {
            System.out.println("(binomial 5 3): " + tiny.binomial(5, 3));
            System.out.println("(binomial 10042, 111): " + tiny.binomial(10042, 111));
        }
    }
    
    
    ;; The result was:
    (binomial 5 3): 10.0
    (binomial 10042, 111): 4.9068389575068143E263
    
    
    ;; Example was borrowed from clartaq @ Stack Overflow
  • ;; Create a namespace named demo.namespace.
    (ns demo.namespace)
    
    ;; Clojure recommends namespaces be at least "two segments" (ie, they should have at least one '.') otherwise it will create a class in the "default package", which is discouraged.
    
    ;; If this declaration appears in a file named "demo/namespace.clj" present in your classpath, it is known as a "lib", "demo/namespace.clj" is the lib's "root resource". See http://clojure.org/libs
    
    ;; From a clean repl you can load the lib using
    user=>(require 'demo.namespace) 
    ; or
    user=>(use 'demo.namespace)
  • ;; This example will illustrate changing between namespaces at the repl
    
    ;; At the repl, the ns macro can be used to create a namespace, but it is used to change the current namespace (be careful of typos)
    user=>(ns demo.namespace)
    nil
    demo.namespace=> ; The prompt at the repl is now "demo.namespace" reflecting that the current namespace is no longer "user".
    
    ;; Add a new function to demo.namespace
    demo.namespace=>(defn foo [] (prn "Hello from demo.namespace"))
    #'demo.namespace/foo
    
    ;; From within "demo.namespace" we can use foo without qualifying it
    demo.namespace=>(foo)
    "Hello from demo.namespace"
    nil
    
    ;; Switch back to the "user" namespace
    demo.namespace=>(ns user)
    nil
    
    ;; We can no longer use "foo" without qualification
    user=> (foo)
    java.lang.Exception: Unable to resolve symbol: foo in this context (NO_SOURCE_FILE:4)
    
    user=> (demo.namespace/foo)
    "Hello from demo.namespace"
    nil
    
    ;; The public symbols of "demo.namespace" can be "referred into" the "user" namespace if desired
    user=> (refer 'demo.namespace)
    nil
    
    ;; foo is now an alias in the "user" namespace which refers to the "demo.namespace/foo" symbol
    user=> (foo)
    "Hello from demo.namespace"
    nil
  • (ns rosettacode.24game
      (:require [clojure.string :as str])
      (:use clojure.test))
    
    (deftest test
     (is (= "ABC" (str/capitalize "abc")))
  • ;; Multiple required namespaces with aliases
    (ns demo.namespace
      (:require [com.example.httplib :as httplib]
                [com.example.otherlib :as otherlib]))
    
  • ;; In clojure 1.4 and higher you can use the refer function from within
    ;; a require which is equivalent to (:use foo only [...]) but still 
    ;; allows you to reference the required namespace:
    (ns my.ns.example
        (:require [my.lib :refer [function1 function2]]))
    
    ;; And :refer :all is equivalent to :use :
    (ns my.ns.example
        (:require [my.lib :refer :all]))
    
  • (ns foo.bar
      (:refer-clojure :exclude [ancestors printf])
      (:require [clojure.contrib sql sql.tests])
      (:use [my.lib this that])
      (:import [java.util Date Timer Random]
        (java.sql Connection Statement)))
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:4594 top

(defmacro ns
  "Sets *ns* to the namespace named by name (unevaluated), creating it
  if needed.  references can be zero or more of: (:refer-clojure ...)
  (:require ...) (:use ...) (:import ...) (:load ...) (:gen-class)
  with the syntax of refer-clojure/require/use/import/load/gen-class
  respectively, except the arguments are unevaluated and need not be
  quoted. (:gen-class ...), when supplied, defaults to :name
  corresponding to the ns name, :main true, :impl-ns same as ns, and
  :init-impl-ns true. All options of gen-class are
  supported. The :gen-class directive is ignored when not
  compiling. If :gen-class is not supplied, when compiled only an
  nsname__init.class will be generated. If :refer-clojure is not used, a
  default (refer 'clojure) is used.  Use of ns is preferred to
  individual calls to in-ns/require/use/import:

  (ns foo.bar
    (:refer-clojure :exclude [ancestors printf])
    (:require (clojure.contrib sql sql.tests))
    (:use (my.lib this that))
    (:import (java.util Date Timer Random)
             (java.sql Connection Statement)))"
  {:arglists '([name docstring? attr-map? references*])
   :added "1.0"}
  [name & references]
  (let [process-reference
        (fn [[kname & args]]
          `(~(symbol "clojure.core" (clojure.core/name kname))
             ~@(map #(list 'quote %) args)))
        docstring  (when (string? (first references)) (first references))
        references (if docstring (next references) references)
        name (if docstring
               (vary-meta name assoc :doc docstring)
               name)
        metadata   (when (map? (first references)) (first references))
        references (if metadata (next references) references)
        name (if metadata
               (vary-meta name merge metadata)
               name)
        gen-class-clause (first (filter #(= :gen-class (first %)) references))
        gen-class-call
          (when gen-class-clause
            (list* `gen-class :name (.replace (str name) \- \_) :impl-ns name :main true (next gen-class-clause)))
        references (remove #(= :gen-class (first %)) references)
        ;ns-effect (clojure.core/in-ns name)
        ]
    `(do
       (clojure.core/in-ns '~name)
       (with-loading-context
        ~@(when gen-class-call (list gen-class-call))
        ~@(when (and (not= name 'clojure.core) (not-any? #(= :refer-clojure (first %)) references))
            `((clojure.core/refer '~'clojure.core)))
        ~@(map process-reference references)))))

Comments top

1 comment(s) for ns.

Good description of use/require/import here:

http://blog.8thlight.com/articles/2010/12/6/clojure-libs-and-namespaces-require-use-import-and-ns

Log in to add a comment.