Comparing characters in Rebol 3
Asked Answered
P

2

5

I am trying to compare characters to see if they match. I can't figure out why it doesn't work. I'm expecting true on the output, but I'm getting false.

character: "a"
word: "aardvark"

(first word) = character ; expecting true, getting false
Pottle answered 31/1, 2014 at 23:15 Comment(0)
D
5

So "a" in Rebol is not a character, it is actually a string.

A single unicode character is its own independent type, with its own literal syntax, e.g. #"a". For example, it can be converted back and forth from INTEGER! to get a code point, which the single-letter string "a" cannot:

>> to integer! #"a"
== 97

>> to integer! "a"  
** Script error: cannot MAKE/TO integer! from: "a"
** Where: to
** Near: to integer! "a"

A string is not a series of one-character STRING!s, it's a series of CHAR!. So what you want is therefore:

character: #"a"
word: "aardvark"

(first word) = character ;-- true!

(Note: Interestingly, binary conversions of both a single character string and that character will be equivalent:

>> to binary! "μ"
== #{CEBC}

>> to binary! #"μ"
== #{CEBC}

...those are UTF-8 byte representations.)

Doenitz answered 31/1, 2014 at 23:26 Comment(2)
I personally think it would be helpful if, at least for the baseline = operator, if single character strings were treated equivalent to characters. The stricter == might still return false. These and other issues discussed in the chat roomDoenitz
Be careful about using actions on string! datatypes. >> pick "test" 2 == #"e"Stefaniastefanie
E
4

I recommend for cases like this, when things start to behave in a different way than you expected, to use things like probe and type?. This will help you get a sense of what's going on, and you can use the interactive Rebol console on small pieces of code.

For instance:

>> character: "a"

>> word: "aardvark"

>> type? first word
== char!

>> type? character
== string!

So you can indeed see that the first element of word is a character #"a", while your character is the string! "a". (Although I agree with @HostileFork that comparing a string of length 1 and a character is for a human the same.)

Other places you can test things are http://tryrebol.esperconsultancy.nl or in the chat room with RebolBot

Ettie answered 1/2, 2014 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.