-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
命名空间概念好难.. 断断续续看了文档还是不懂, 我把进度在这里整理了
首先 Google Code 上说明写的很清晰: http://code.google.com/p/clojure-doc-en2ch/wiki/Chapter_7
REPL 默认的 ns 是 user, user 中含有 clojure.core, 新创建的 ns 里不一定有
默认的 clojure 对象是从所有的 ns 可以访问的
可以通过 *ns* 来查看, 使用 in-ns 可以切换命名空间:
user=> *ns*
#<Namespace user>
user=> (in-ns 'greetings)
#<Namespace greetings>
greetings=> clojure.core/*ns*
#<Namespace greetings>
greetings=> (clojure.core/println "Hello, World!")
Hello, World!
nil问题是命名空间相互间意义是什么, 怎样相互引用, 主入口怎样来?
clojure.core/println 中的 / 表示引用一个 ns, 但是点号是什么?
refer 和 alias 只是从已有的模块里导入引用, 理解目前没问题
greetings=> map
java.lang.Exception: Unable to resolve symbol: map in this context (NO_SOURCE_FILE:0)
greetings=> (clojure.core/refer 'clojure.core :only '(map set))
nil
greetings=> map
#<core$map clojure.core$map@41a68961>
greetings=> (alias 'core 'clojure.core)
nil
greetings=> (core/println "s")
s
nilload 也是, 从文件加载模块是习见的, 我在 REPL 对应目录新建 lib.clj
(defn f [x] (println x))然后在 REPL 运行代码就把文件给引入了:
greetings=> (load-file "./lib.clj")
#'greetings/f
greetings=> (f "x")
x
nilrequire 是相对更高级的接口, 我创建了 example/lib.clj 文件如下:
(defn g [] (println "inside"))
就能从 REPL 中将其引用成功..
greetings=> (require 'example.lib)
nil
greetings=> (g)
inside
nil
greetings=> (require '(example/lib))
nil但是很古怪的是, 其中一直写法有报错, 甚至 use 语法一起报错
greetings=> (require '[example.lib :as lib])
java.lang.Exception: namespace 'example.lib' not found (NO_SOURCE_FILE:0)而通过 import 导入 Java 对象又是很好懂的了
greetings=> (import 'java.util.Date)
java.util.Date
greetings=> (new Date)
#<Date Sun Nov 04 17:32:40 CST 2012>参考:
Clojure-JVM上的函数式编程语言(7) 命名空间 作者: R. Mark Volkmann
Huangz/Notes » Clojure » 命名空间
Clojure Handbook 2.10 命名空间