^2 exhibits postfix behavior

julia> 4 ^2
16

But

julia> ^2(4)

ERROR:** syntax: “^” is not a unary operator

What is the rational for this behavior?

The problem is that it gets parsed as ^(2*4).

julia> ^(2,3)
8

I know that. My question was about ^2(n).

OK, thanks.

Yes, the key is that the function is not ^2, it’s simply ^. So it’s not that ^2 is a postfix operator applied to 4, but rather that ^ is an infix operator between 2 and 4. It’s an infix operator with very high precedence.

Hopefully that gets at the rationale that you’re after here. You could manually create a square operator, but it’s not done automatically:

julia> square(x) = x^2
square (generic function with 1 method)

julia> square(4)
16
3 Likes

Thanks for the explanation, it’s very helpful!

would you please mark the correct reply as “solution”?