Likan Zhan
Likan Zhan

Reputation: 1076

What is the difference between `(1)(2)` and `x = 1; (x)(2)` in Julia?

What is the difference between (1)(2) and x = 1; (x)(2) as being shown below?

julia> (1)(2)
2

# but
julia> x = 1
1
julia> (x)(2)
ERROR: MethodError: objects of type Int64 are not callable

Thanks.

Quoted from here.

Upvotes: 3

Views: 62

Answers (2)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42234

While Simeon exactly described what happened, note that in similar cases you can always use dump(quote; ...; end) to get the information what is going on:

julia> dump(quote
       (1)(2)
       end)
Expr
  head: Symbol block
  args: Array{Any}((2,))
    1: LineNumberNode
      line: Int64 2
      file: Symbol REPL[2]
    2: Expr
      head: Symbol call
      args: Array{Any}((3,))
        1: Symbol *
        2: Int64 1
        3: Int64 2

julia> dump(quote
       (x)(2)
       end)
Expr
  head: Symbol block
  args: Array{Any}((2,))
    1: LineNumberNode
      line: Int64 2
      file: Symbol REPL[3]
    2: Expr
      head: Symbol call
      args: Array{Any}((2,))
        1: Symbol x
        2: Int64 2

You can see that the first case parses to multiplication and the second to a function call.

Upvotes: 3

Simeon Schaub
Simeon Schaub

Reputation: 775

Juxtaposition of number literals is special cased in Julia's parser, so similar to how 2x parses as 2 * x, (1)(2) (or equivalently 1(2)) parses as 1 * 2. (x)(2) on the other hand is just regular function call syntax, just as x(2) is. This errors if x is a number, because numbers in Julia are not callable.

Upvotes: 5

Related Questions