Julia REPL 告诉我输出
'c'+2
Run Code Online (Sandbox Code Playgroud)
'e': ASCII/Unicode U+0065 (category Ll: Letter, lowercase)
但输出是
'c'+2-'a'
Run Code Online (Sandbox Code Playgroud)
是4。
我同意字符通过 ASCII 代码识别为数字这一事实。但我对这里的类型推断感到困惑:为什么第一个输出是字符,第二个输出是整数?
关于约定的动机,它类似于时间戳和间隔。时间戳之间的差异是一个时间间隔,因此您可以在一个时间戳上添加一个时间间隔以获得另一个时间戳。但是,您不能添加两个时间戳,因为这没有意义\xe2\x80\x99\xe2\x80\x94两个时间点的总和应该是多少?两个字符之间的差异是它们在代码点空间中的距离(整数);因此,您可以向 char 添加一个整数,以获得另一个 char,该 char\xe2\x80\x99s 偏移了那么多代码点。您可以\xe2\x80\x99t 添加两个字符,因为添加两个代码点并不是一个有意义的操作。
\n为什么首先允许比较字符和差异?因为通常使用这种算术和比较来实现解析代码,例如解析各种基数和格式的数字。
\n原因是:
julia> @which 'a' - 1
-(x::T, y::Integer) where T<:AbstractChar in Base at char.jl:227
julia> @which 'a' - 'b'
-(x::AbstractChar, y::AbstractChar) in Base at char.jl:226
Run Code Online (Sandbox Code Playgroud)
Char与整数相减为Char。这是例如'a' - 1。
然而,减二Char是整数。这是例如'a' - 'b'。
请注意,对于Char和 整数,都定义了加法和减法,但对于 2Char只定义了减法:
julia> 'a' + 'a'
ERROR: MethodError: no method matching +(::Char, ::Char)
Run Code Online (Sandbox Code Playgroud)
这确实有时会导致依赖操作顺序的棘手情况,如下例所示:
julia> 'a' + ('a' - 'a')
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> 'a' + 'a' - 'a'
ERROR: MethodError: no method matching +(::Char, ::Char)
Run Code Online (Sandbox Code Playgroud)
另请注意,使用Char和 整数时,不能Char从整数中减去:
julia> 2 - 'a'
ERROR: MethodError: no method matching -(::Int64, ::Char)
Run Code Online (Sandbox Code Playgroud)
动机:
c - '0'如果您知道字符是数字,则将字符转换为其十进制表示形式;'0' + d。我已经使用 Julia 多年了,我可能使用过这个功能一两次,所以我不会说它是非常普遍需要的。