Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic with Chars in Julia

Tags:

char

ascii

julia

Julia REPL tells me that the output of

'c'+2

is 'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase) but that the output of

'c'+2-'a'

is 4.

I'm fine with the fact that Chars are identified as numbers via their ASCII code. But I'm confused about the type inference here: why is the first output a char and the second an integer?

like image 322
fact Avatar asked Jun 14 '26 10:06

fact


1 Answers

Regarding the motivation for conventions, it’s similar to time stamps and intervals. The difference between time stamps is an interval and accordingly you can add an interval to a time stamp to get another time stamp. You cannot, however, add two time stamps because that doesn’t make sense—what is the sum of two points in time supposed to be? The difference between two chars is their distance in code point space (an integer); accordingly you can add an integer to a char to get another char that’s offset by that many code points. You can’t add two chars because adding two code points is not a meaningful operation.

Why allow comparisons of chars and differences in the first place? Because it’s common to use that kind of arithmetic and comparison to implement parsing code, eg for parsing numbers in various bases and formats.

like image 197
StefanKarpinski Avatar answered Jun 17 '26 09:06

StefanKarpinski



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!