项目作者: marius311

项目描述 :
Julia macro for writing more concise functions with a "self"-like argument
高级语言: Julia
项目地址: git://github.com/marius311/SelfFunctions.jl.git
创建时间: 2018-09-20T20:14:34Z
项目社区:https://github.com/marius311/SelfFunctions.jl

开源协议:

下载


SelfFunctions.jl

SelfFunctions.jl provides a macro, @self, which gives functions an implicit argument of a specified type, and lets you implicitly access the fields of that type from inside the function. It is quite similar to how C++ class member functions work.

It is most useful when you have a struct storing “parameters” of a model, and then are writing many mathematical functions that use those parameters. SelfFunctions.jl lets you write those functions succinctly and without obscuring the mathematics.

To install,

  1. add https://github.com/marius311/SelfFunctions.jl.git

An example,

  1. using SelfFunctions
  2. # struct which stores parameters of a model
  3. struct Rosenbrock{T}
  4. a::T
  5. b::T
  6. end
  7. # define some mathematical function
  8. @self Rosenbrock rosen(x,y) = (a-x)^2 + b*(y-x^2)^2
  9. # create model and call function
  10. r = Rosenbrock(1, 2)
  11. rosen(r, 3, 4) # returns 54

The magic is that the macro rewrites,

  1. @self Rosenbrock rosen(x,y) = (a-x)^2 + b*(y-x^2)^2

to

  1. rosen(self::Rosenbrock,x,y) = (self.a-x)^2 + self.b*(y-x^2)^2

Note that because the fields of Rosenbrock are known, the macro knows to only modify a and b. It is moderately smart about which variables to modify; many, but not all, cases should work. Note also that inner calls to “self” functions do not explicitly need to pass the first argument, this is inserted automatically:

  1. @self Rosenbrock shifted_rosen(x,y) = rosen(x+1, y+1)
  2. shifted_rosen(r, 2, 3) # gives 54 as before

Thanks to @fcard for the cool trick which allows this to work with no performance overhead (see also https://github.com/fcard/SelfFunctions.jl which does basically the same thing but with different syntax, although as of this writing is not compatible with Julia 1.0).

Capturing type parameters works as you might expect,

  1. @self Rosenbrock{T} rosen(x,y) where {T} = (a-x)^2 + b*(y-x^2)^2 + zero(T)