Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring to character comparison counterintuitive results in Julia 1.0

Tags:

julia

I am new to the Julia language and see some strange behavior when comparing a substring to a character.

I would think that the first comparison below, at least, should evaluate to true.

Could someone please show me how to compare these two values and (bonus) point me in the direction as to why this counterintuitive result is the case?

julia> sq = "abcd"

julia> sq[1] == "a"
false

julia> isequal(sq[1],"a")
false
like image 311
qbzenker Avatar asked Jan 02 '23 19:01

qbzenker


1 Answers

sq[1] returns a Char. Use sq[1:1] to get a String.

You can check what sq[1] returns in REPL:

julia> sq[1]
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

so you have:

julia> sq[1] == 'a'
true

as this compares Char to Char.

on the other hand with sq[1:1] you have:

julia> sq[1:1]
"a"

julia> sq[1:1] == "a"
true

The reason for this behavior is that strings are considered as collections. Similarly if you have an array x = [1,2,3] you do not expect that x[1] == [1] but rather x[1] == 1.

like image 132
Bogumił Kamiński Avatar answered Jun 11 '23 06:06

Bogumił Kamiński