Clojure:字符文字平等

imr*_*las 3 string character clojure

我有点天真地认为,Clojure中的单个字符串无论生成方式如何都是相同的.

(= "G" "G")
=>
true

(= "G" \G)
=>
false

(= \G \G)
=>
true
Run Code Online (Sandbox Code Playgroud)

事实证明并非如此.有谁能解释为什么?

Sam*_*tep 5

一个字符是一样的一个字符的字符串.相反,单字符串可以被认为是其第一个且唯一的项是字符的序列.

(type "G")
;=> java.lang.String
(type \G)
;=> java.lang.Character

(count "G")
;=> 1
(count \G)
;=> UnsupportedOperationException count not supported on this type: Character

(seq "G")
;=> (\G)
(seq \G)
;=> IllegalArgumentException Don't know how to create ISeq from: java.lang.Character

(first "G")
;=> \G
(first \G)
;=> IllegalArgumentException Don't know how to create ISeq from: java.lang.Character
Run Code Online (Sandbox Code Playgroud)


ez1*_*1sl 5

仅仅是为了完整性...与Clojure不同,ClojureScript的行为与OP推测完全相同.由于Javascript没有字符类型,只有String,ClojureScript字符被实现为单字符字符串.

在ClojureScript REPL中:

(= "G" "G")
;=> true

(= "G" \G)
;=> true

(= \G \G)
;=> true

(type "G")
;=> #object[String "function String() {
;=>    [native code]
;=> }"]

(type \G)
;=> #object[String "function String() {
;=>    [native code]
;=> }"]
Run Code Online (Sandbox Code Playgroud)