Reputation: 520
I presumed, somewhat naively perhaps, that single character strings in Clojure would be equal regardless of how they were generated.
(= "G" "G")
=>
true
(= "G" \G)
=>
false
(= \G \G)
=>
true
Turns out not to be the case. Can anyone explain why?
Upvotes: 3
Views: 1195
Reputation: 2429
Just for the sake of completeness... ClojureScript, unlike Clojure, behaves exactly as the OP presumed. Since Javascript does not have the character type, just String, ClojureScript characters are implemented as single-character strings.
In 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]
;=> }"]
Upvotes: 5
Reputation: 13324
A character is not the same as a single-character string. Rather, a single-character string can be thought of as a sequence whose first and only item is a character.
(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
Upvotes: 5