我正在关注clojure.spec的指南(http://clojure.org/guides/spec).我被之间的区别感到困惑alt,并or进行序列规范.
对我来说,以下两个例子同样有效.那两者之间的区别是什么?
; Use `alt`
(s/def ::config (s/* (s/cat :prop string?
:val (s/alt :s string? :b boolean?))))
(s/explain ::config ["-server" "foo" "-verbose" true "-user" 13])
; Use `or`
(s/def ::config (s/* (s/cat :prop string?
:val (s/or :s string? :b boolean?))))
(s/explain ::config ["-server" "foo" "-verbose" true "-user" 13])
Run Code Online (Sandbox Code Playgroud) (class (range 10))
;=> clojure.lang.LazySeq
(class (seq (range 10))
;=> clojure.lang.ChunkedCons
Run Code Online (Sandbox Code Playgroud)
据我了解,LazySeq已经是一个序列,因为:
(seq? (range 10))
;=> true
Run Code Online (Sandbox Code Playgroud) 我的谜题是以下示例:
(defmacro macro1 [x]
(println x))
(defn func1 [x]
(println x))
(defmacro macro2 [x]
`(macro1 ~x)
(func1 x))
(defmacro macro3 [x]
(func1 x)
`(macro1 ~x))
(println "macro2")
(macro2 hello)
(println "macro3")
(macro3 hello)
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,输出是:
macro2
hello
macro3
hello
hello
Run Code Online (Sandbox Code Playgroud)
为什么macro2和macro3的输出不同?根据我的理解,宏内部宏的所有调用都可以用函数代替(除了重用的原因).我的理解有什么不对吗?
谢谢迈克尔的澄清.我的一般问题是如何在宏内部使用函数或宏来操作s-expression.我想知道它们是否可以交换使用,除了它们在不同的阶段被唤醒.另一个例子:
(defn manipulate-func [x]
(list + x 1))
(defmacro manipulate-macro [x]
(list + x 1))
(defmacro macro1 [x y]
[(manipulate-func x) `(manipulate-macro ~y)])
(println (clojure.walk/macroexpand-all '(macro1 (+ 1 2) (+ 3 4))))
;; [(#<core$_PLUS_ clojure.core$_PLUS_@332b9f79> (+ 1 2) 1) (#<core$_PLUS_ …Run Code Online (Sandbox Code Playgroud) 为什么不进行类型检查extractEither?
data MyEither a b = MyLeft a | MyRight b
deriving (Read, Show)
extractEither :: MyEither a b -> c
extractEither (MyLeft p) = p
Run Code Online (Sandbox Code Playgroud)
编译器显示:
Couldn't match type `a' with `c'
`a' is a rigid type variable bound by
the type signature for extractEither :: MyEither a b -> c
at /Users/tongmuchenxuan/playground/test.hs:5:1
`c' is a rigid type variable bound by
the type signature for extractEither :: MyEither a b -> c
at /Users/tongmuchenxuan/playground/test.hs:5:1
In the expression: …Run Code Online (Sandbox Code Playgroud)