Clojure NS
ns 类似 java 的 import 包系统。
use
使用样例:
(ns org.currylogic.damages.http.expenses) (use 'org.danlarkin.json) (use 'clojure.xml) (defn import-transactions-xml-from-bank [url] (let [xml-document (parse url)] ;; more code here (defn totals-by-day [start-date end-date] (let [expenses-by-day (load-totals start-date end-date)] (encode-to-str expenses-by-day)))
use takes all public functions from the namespace and includes them in the current namespace.
encode-to-str 和 parse 是来自于引入的外部函数,使用 use 可以获取到这些函数,但是会摸不到头脑:这些函数是在哪里定义的?
更简洁的,使用 require.
require
使用样例:
(ns org.currylogic.damages.http.expenses) (require '(org.danlarkin [json :as json-lib])) (require '(clojure [xml :as xml-core])) (defn import-transactions-xml-from-bank [url] (let [xml-document (xml-core/parse url)] ;; more code here (defn totals-by-day [start-date end-date] (let [expenses-by-day (load-totals start-date end-date)] (json-lib/encode-to-str expenses-by-day)))
这样在调用外部函数的时候,能明确知道函数来源于哪里,并且可以为外部的ns设置别名。
reload & reload-all
使用样例:
(use 'org.currylogic.damages.http.expenses :reload) (require '(org.currylogic.damages.http [expenses :as exp]) :reload)
引入其他 ns 中的函数, 当这些函数发生改动,使用 reload 可以得到更新。(:reload can be replaced with :reload-all to reload all libraries that are used either directly or indirectly by the specified library.)
import
使用样例:
(import '(org.apache.hadoop.hbase.client HTable Scan Scanner) '(org.apache.hadoop.hbase.filter RegExpRowFilter StopRowFilter))
import 用于导入 java 包。
简洁的方式
(ns my-great-project.core "This namespace is CRAZY!" (:use [clojure.string :only [split join]] :reload) (:require clojure.stacktrace [clojure.test :as test]) (:import (java.util Date GregorianCalendar)))