Last active
January 8, 2022 17:47
-
-
Save CWKSC/d71ab509d96c314c77cf89f68147a953 to your computer and use it in GitHub Desktop.
Kotlin with 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
function changeSymbol(target, to, expr) | |
function dfs(expr) | |
args = expr.args | |
for i in 1:length(args) | |
arg = args[i] | |
if arg isa Expr | |
dfs(arg) | |
elseif arg isa Symbol | |
if arg == target | |
args[i] = to | |
end | |
end | |
end | |
end | |
dfs(expr) | |
expr | |
end | |
macro with(var, expr) | |
symbols = fieldnames(typeof(eval(var))) | |
for symbol in symbols | |
changeSymbol(symbol, :($var.$symbol), expr) | |
end | |
expr | |
end | |
mutable struct Foo | |
x::Int | |
y::String | |
end | |
foo = Foo(42, "meow") | |
macroexpand(Main, :(@with foo begin | |
x = 1 | |
y = "2" | |
end)) | |
@with foo begin | |
x = 1 | |
y = "2" | |
end | |
println(foo) |
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
function changeSymbol(target, to, expr) | |
function dfs(expr) | |
args = expr.args | |
for i in 1:length(args) | |
arg = args[i] | |
if arg isa Expr | |
dfs(arg) | |
elseif arg isa Symbol | |
if arg == target | |
args[i] = to | |
end | |
end | |
end | |
end | |
dfs(expr) | |
expr | |
end | |
mutable struct Foo | |
x::Int | |
y::String | |
end | |
function with(var, expr) | |
symbols = fieldnames(typeof(var)) | |
for symbol in symbols | |
changeSymbol(symbol, :($var.$symbol), expr) | |
end | |
expr | |
end | |
function boo() | |
foo = Foo(42, "meow") | |
println(foo) | |
eval(with(foo, quote | |
x = 1 | |
y = "2" | |
end)) | |
println(foo) | |
end | |
boo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment