Julia equivalent to a static member function in C++/MATLAB

279 views
Skip to first unread message

Joel Andersson

unread,
Sep 25, 2015, 11:56:46 AM9/25/15
to julia-users
Hi,

In C++ or in MATLAB I would use static member functions to keep the constructors nice and simple, e.g.
class MyMatrix {
 
public:
  static MyMatrix zeros(int n, int m);
  static MyMatrix ones(int n, int m);
  static MyMatrix eye(int n);
 
...
};

Which allows me to create class instances with an IMO natural syntax, which should also be relatively efficient due to return value optimization:
MyMatrix x = MyMatrix::zeros(3,4);

In MATLAB, I would do the same with a static method, e.g.:
x = MyMatrix.zeros(3,4);

What is the equivalent way to do it in Julia? I have seen discussions of whether and how to overload the dot operator ".", but I did not fully understand if this discussion applies to the above case or if that's already possible somehow.

Best regards,
Joel

Steven G. Johnson

unread,
Sep 25, 2015, 12:00:00 PM9/25/15
to julia-users


On Friday, September 25, 2015 at 11:56:46 AM UTC-4, Joel Andersson wrote:
Hi,

In C++ or in MATLAB I would use static member functions to keep the constructors nice and simple, e.g.
class MyMatrix {
 
public:
  static MyMatrix zeros(int n, int m);
  static MyMatrix ones(int n, int m);
  static MyMatrix eye(int n);
 
...
};

Which allows me to create class instances with an IMO natural syntax, which should also be relatively efficient due to return value optimization:
MyMatrix x = MyMatrix::zeros(3,4);


In Julia, you can do the same thing, it is just spelled differently.  You could do
     x = zeros(MyMatrix, 3, 4)
where you have defined
     Base.zeros(::Type{MyMatrix}, m, n) = .....

Joel Andersson

unread,
Sep 25, 2015, 12:06:23 PM9/25/15
to julia-users
Great, thanks! Joel

Greg Plowman

unread,
Sep 25, 2015, 5:15:29 PM9/25/15
to julia-users
 
In Julia, you can do the same thing, it is just spelled differently.  You could do 
   x = zeros(MyMatrix, 3, 4)
where you have defined
     Base.zeros(::Type{MyMatrix}, m, n) = .....
Of course in Julia you can do anything you want.
However, is it recommended to redefine the meaning of generic functions?
I would assume zeros(MyMatrix,3,4) creates a 3x4 Array{MyMatrix,2}

Eric Forgy

unread,
Sep 25, 2015, 10:37:39 PM9/25/15
to julia-users
You probably know this, but the way dispatch works in Julia, it will look for a function matching the signatures. Since, presumably, MyMatrix is not in base Julia, that zeros function will do whatever you want it to do because you have yo implement it.

Joel Andersson

unread,
Sep 26, 2015, 3:23:34 AM9/26/15
to julia...@googlegroups.com
Yes, this is all clear. Joel

Reply all
Reply to author
Forward
0 new messages