Method of struct

Since Julia doesn’t allow any function declaration other than constructors inside struct right now, one can imagine a new syntax that allows the declaration of the functions that are suitable for the dot syntax. For example,

struct Foo
    x
    function f(foo::Foo, x) end
end

f(foo:Foo, x) = (foo.x = x)

In this way, Julia can treat foo.f(x) as f(foo, x). And it also makes autocompleetion easier to implement in editors.

Agreed.

Maybe. But the dot syntax seems so natural in many cases that the same issue will be raised again and again as long as Julia attracts people. Why not make it a syntax sugar?

Hasn’t that been explained sufficiently?

I guess it depends who you ask :slightly_smiling_face: There’re things that one can manage to live without but will be happier to live with. Again, I’m not talking about piping or chaining for which elegant alternatives have been shown to exist.

You can do that like this:

mutable struct Foo
    x::Float64
end
function Base.getproperty(obj::Foo, sym::Symbol)
    if sym == :f
        # return (val) -> setfield!(obj, :x, val)
        return (val) -> (obj.x = val)
    else
        return getfield(obj, sym)
    end
end

Then you can do

julia> obj = Foo(23.1)
Foo(23.1)

julia> obj.f(-4.2);

julia> obj
Foo(-4.2)

Do this for as many functions as you like. But it is not likely to become something that happens automatically.

I see the hornet’s nest has been kicked again :wink:

Thank you, I have added this to my running list of Julia macros which hope to address chaining/piping/threading/currying/partial evaluation/whatever it’s called. I have now collected links to eleven such packages.

I feel like my proposal (plus addendum) is now mature enough that I can split off into its own proposal thread.

It’s good except that it may not be (elegantly) generalized to more complicated cases and it adds a performance penalty.

due to constant propagation, there is no performance penalty.

it’s just a dog darn ugly solution.