Created
March 11, 2019 15:17
-
-
Save christopher-dG/49a600b680cf692bb9947f7a20f5ac20 to your computer and use it in GitHub Desktop.
Silly POC of OO-style instance methods in Julia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tablename(x::Symbol) = Symbol(:methtab_, x) | |
macro instancemethod(T::Symbol, ex::Expr) | |
@assert ex.head ∈ (:function, :(=)) | |
table = tablename(T) | |
name = ex.args[1].args[1] | |
insert!(ex.args[1].args, 2, :(this::$T)) | |
quote | |
$(esc(ex)) | |
$table[$(QuoteNode(name))] = $name | |
end | |
end | |
macro OO(ex::Expr) | |
@assert ex.head === :struct | |
T = ex.args[2] | |
table = esc(tablename(T)) | |
quote | |
const $table = Dict{Symbol, Function}() | |
$(esc(ex)) | |
function Base.getproperty(x::$T, name::Symbol) | |
return if haskey($table, name) | |
(args...; kwargs...) -> $table[name](x, args...; kwargs...) | |
else | |
getfield(x, name) | |
end | |
end | |
end | |
end | |
@OO mutable struct Foo | |
x::Int | |
end | |
@instancemethod Foo set_x(x::Int) = this.x = x | |
f = Foo(1) | |
f.set_x(10) | |
@show f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment