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

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?



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
++ (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
[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:


Thanks for your answers :slight_smile: I’ll just use a different name.

See 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.


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

for example, this one:

:eight_spoked_asterisk: : \:eight_spoked_asterisk:

(that is a joke :slight_smile: )

May I suggest :dizzy: (\: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).


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

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

julia> 2 *² 3

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