Looping over string representation of number in Julia unexpected behaviour

269 views Asked by At

I'm trying to understand why int("0") > 0 evaluates to false while all([int(i) > 0 for i in "0"]) evaluates to true. Interestingly, [all(i != "0" for i in "0"] also evaluates to true.

How can I get my list comprehension to evaluate correctly, that is, catch the "0"?

1

There are 1 answers

0
DSM On BEST ANSWER

int is being called with different types, because iterating over a string is giving Char objects, not strings of length 1:

julia> typeof("0")
ASCIIString (constructor with 2 methods)

julia> [typeof(x) for x in "0"]
1-element Array{Type{Char},1}:
 Char

and when given a Char, Julia's int is more like Python's ord:

julia> int("0")
0

julia> int("0"[1])
48

which gives rise to what you see:

julia> [int(i) for i in "0"]
1-element Array{Int32,1}:
 48

julia> [int(i) > 0 for i in "0"]
1-element Array{Bool,1}:
 true

julia> all([int(i) > 0 for i in "0"])
true

There are lots of ways you could get this to behave as you expect, e.g. use parseint or simply convert back to a string:

julia> [parseint(i) for i in "0"]
1-element Array{Int32,1}:
 0

julia> [int(string(i)) for i in "0"]
1-element Array{Int32,1}:
 0