# Creating a function called **

Hi !

I’m trying to define an operator called **, using something like

function **(a,b)
return a+b+1 # or whatever
end


but Julia won’t let me – it’s just warning me that ** is not used for exponentiation. But ** is a good name for me!

(it works with ++ instead of **, for example)

Any idea?

thanks!
Pierre

2 Likes

Interesting? But are you sure that it works with ++?

It does not work for me

julia> function ++(a,b)
return a+b+1 # or whatever
end
++ (generic function with 1 method)

julia> ++(1,2)
ERROR: MethodError: no method matching +(::Int64, ::Int64, ::Int64)
You may have intended to import Base.:+
Closest candidates are:
+(::Any, ::Any) at REPL[11]:1
Stacktrace:
[1] ++(a::Int64, b::Int64)
@ Main ./REPL[14]:2
[2] top-level scope
@ REPL[15]:1

@leonandonayre Your example fails because of precedence of the + operator. You can run your function by calling (++)(1, 2). For why the OP can’t even define **, maybe someone else can answer.

1 Like

Yeah, ** is special cased in the parser itself to throw this particular error: julia/julia-parser.scm at d7d2b0c692eb6ad409d7193ba8d9d42972cbf182 · JuliaLang/julia · GitHub

My guess was that this was to help guide Python users to the correct syntax in Julia, and after digging through the git history it turns out I was right:

6 Likes

See https://github.com/JuliaLang/julia/pull/39089. We just didn’t really come up with a convincing enough use case at the time. If you have a concrete use for this, feel free to chime in on the discussion there.

2 Likes

Take a look at the unicode symbols, maybe there is one even better for your use case:

https://docs.julialang.org/en/v1/manual/unicode-input/

for example, this one:

: \:eight_spoked_asterisk:

(that is a joke )

May I suggest (\:dizzy:), which in some fonts has two stars.

Edited to add - when I actually posted this the symbol changed after sending to a single star, I meant this:

1 Like

Note that emoji like :dizzy: and :eight_spoked_asterisk: are in Unicode category So (Symbol, other) and are typically not parsed as infix operators by Julia.

That being said, there are plenty of infix operators to choose from. My visual favorite is ⨳ (\smashtimes).

4 Likes

Another thing you’re allowed to do is stick unicode modifiers on infix operators to make new operators with the same precence. For example:

julia> *̂(a,b) = a + b
*̂ (generic function with 1 method)

julia> 1 *̂ 2
3

julia> *²(a, b) = (a * b)^2
*² (generic function with 1 method)

julia> 2 *² 3
36

2 Likes

In fact, I am now using \cdot (how do I make it visible in this post??)