Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: character literal equality

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?

like image 296
imranolas Avatar asked Jan 28 '26 05:01

imranolas


1 Answers

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
like image 194
Sam Estep Avatar answered Jan 30 '26 19:01

Sam Estep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!