Julia: allow `x.1` getfield syntax?

Created on 3 Feb 2017  路  4Comments  路  Source: JuliaLang/julia

I expect that there might already be an issue about this, but I haven't been able to find it. Putting a numeric literal after a dot has odd behavior:

julia> x=2;

julia> x.1
ERROR: syntax: extra token "0.1" after end of expression

julia> [x.1]
1脳2 Array{Float64,2}:
 2.0  0.1

Basically, it is parsed as a sequence of two expressions, which doesn't seem useful or clear to me. It would be more useful to allow x.1, x.2, etc. to do field access. Accessing fields by constant index is important since it's easy to type infer. This also gives you a convenient way to access object components by index without implementing getindex.

It's consistent; in a.b the b part is a quoted literal, and the integer here can also be treated as a quoted literal.

This seems to work with a wide range of expressions before the dot; f(x).1, [1].1 etc. all behave the same. One exception is (2).1, which does multiplication, but I think that can be left alone or just disallowed. Am I missing anything here?

breaking decision parser

Most helpful comment

Accessing fields by index seems pretty uncommon; my first reaction is to leave this as a parser error (maybe with a clearer error message) in the hopes that we can figure out some better use for it in the future.

All 4 comments

we used to have this in parens but took it out due to the broadcast ambiguity. writing getfield for this is more obvious, and it's not that widely used.

That was pretty different though, since in x.(i) the i was evaluated, while x.i only works with literals. True this is not widely used, but the current interpretation of x.1 is obscure to the point of being a bug. There isn't really anything else x.1 could mean, other than a parse error.

Accessing fields by index seems pretty uncommon; my first reaction is to leave this as a parser error (maybe with a clearer error message) in the hopes that we can figure out some better use for it in the future.

It seems like this has actually always been partially implemented?

julia> (1, 2, 3). 2
2

Which also means that until Julia 1.0, we had this:

julia> im. 1
false

julia> im. 2
true
Was this page helpful?
0 / 5 - 0 ratings