Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia macro that generates accessors

I need a macro that generates accessor functions in the Julia programming language. With a struct like this:

struct Account
  account_number::String
  balance::Float64
end

I want it to generate this code:

  account_number(acc::Account) = acc.account_number
  balance(acc::Account) = acc.balance

And I want to use it like so:

@generate_accessors Account

I have searched the internet and found the Accessors.jl package, but it does not seem to be related to my issue. There is quite a Julia community so I hope a macro like this exists somewhere. Unfortunately I do not have enough Julia experience to implement such a macro myself, I don't even know if such a macro can be made at all. Thanks for any help of pushes in the right direction.

like image 617
TradingDerivatives.eu Avatar asked Oct 21 '25 17:10

TradingDerivatives.eu


1 Answers

I do not know of a library that has such a macro but creating a basic one is not too difficult:

# accessor(:foo, FooBar) ->  quote foo(x::FooBar) = x.foo end
accessor(field, type) = :($(esc(field))(x::$type) = x.$field)

macro generate_accessors(type)
  definitions = (accessor(s, type) for s in fieldnames(eval(type)))
  Expr(:block, definitions...)
end
julia> struct FooBar
           foo
           bar
       end

julia> @generate_accessors FooBar
bar (generic function with 1 method)

julia> foo(FooBar(1,2))
1

julia> bar(FooBar(1,2))
2
like image 96
ahnlabb Avatar answered Oct 23 '25 06:10

ahnlabb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!