Overload call to do multiplication on numbers?


#1

I really like the 2x syntax, and get tired of writing stars.

edit: actual example…

function (x::Float64)(y)
    x*y
end
a = 2.0
a(2+2)

That looks like a hilariously bad idea, but I can’t find any actual problems with this. Anything I missed?


#2

This already works without that definition though:

julia> 2.0pi
6.283185307179586

julia> 2.0(2+2)
8.0

julia> 2.0sin(pi)
2.4492935982947064e-16

#3

Sorry about that, I changed my example but didn’t test :slight_smile: What didn’t work without the definition was:

a = 2.0
a(2+2)

#4
julia> pi(2+2)
ERROR: MethodError: objects of type Irrational{:π} are not callable

julia> a = 2
2

julia> a(2+2)
ERROR: MethodError: objects of type Int64 are not callable

But I get what you mean.

It looks like function call syntax, so for the examples above I would expect to call a function pi and a respectively.


#5

Sorry again, I edited my second post (I should really wait to be on a computer before replying…)

My motivating example was writing sin(2pi(x+y)) by accident and wondering if that could work.


#6

It’s definitely doable, but it seems a bit dangerous. I wouldn’t want to have sin = 666 somewhere and then write sin(x + y) later, thinking that I’m calling the sin function but actually just be multiplying x + y by the number of the beast.


#7

I really like that in Mathematica a b Lowers to a*b. This would probably be horribly invasive and dangerous to implement in Julia but man would I love to be able to write sin(2pi (x+y)) and have the space between 2pi and (x+y) be understood as multiplication.


#8

That’s fair enough, this feature, while very cool, is also fairly dangerous. For those interested:

function build_subtypes(T)
    concretes = [t for t in subtypes(T) if isempty(subtypes(t))]
    abstracts = [t for t in subtypes(T) if !isempty(subtypes(t))]
    types = []
    append!(types, concretes)
    for t in abstracts
        append!(types, build_subtypes(t))
    end
    types
end

for T in build_subtypes(Number)
    @eval begin
        function (x::$T)(y)
            x*y
        end
    end
end

#9

Space is already used as a separator in matrices, so sin.([2pi (x+y)]) would be ambiguous…


#10

Right, I had a feeling there was something that would straight up clash with spaces as multiplication. How could I forget row vectors and matrices!