ジュリアの学習( 6 ) :表現とマクロ


まず、ジュリアの公式docからコピーされたプレゼンテーションの1つの段落を引用する必要があります.

"The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros operating at the level of abstract syntax trees(AST). In contrast, preprocessor "macro" systems, like that of C and C++, perform textual manipulation and substitution before any actual parsing or interpretation occurs. Because all data types and code in Julia are represented by Julia data structures, powerful reflection capabilities are available to explore the internals of a program and its types just like any other data."


私が今日理解している限りでは、ジュリアで書かれたコードは、まずExpertとしてコンパイラによって解析されます.コンパイラは、関数eval()がどのように動作するかと同じ方法でそれらを実行します.この点で、ジュリアのすべては、表現です.
以下は私の学習ノートです.
ex = :(a + b)           # define an expression as :(expression)
println("ex: ", typeof(ex))    # Expr

x = :(ab)               # see what it gives if there is no operator or functions in expression
println("x: ", typeof(x))    # Symbol

println(ex.head, ", ", ex.args)


println("dump(ex):  ") 
dump(ex) ##  equivalent to Meta.@dump :expr


# to define multiple-line expression, one should use: quote ... end
ex1 = quote
a + b
end
println("ex1: ", typeof(ex1))
実行出力

式は文字列から解析することができます( srcファイル内のコードや端末で入力された文字列はすべて文字列です).
ex = :(a + b)
expr_str = "a + b"
ex2 = Meta.parse(expr_str)


println("ex2: ", typeof(ex2))

println("ex == ex2?? answer is : ", ex == ex2)
println("dump(ex2):  ") 
dump(ex2) 

実行出力

また、Expr()を使って式を定義することも可能です
ex = :(a + b)
ex3 = Expr(:call, :+, :a::Symbol, :b::Symbol)
println("ex == ex3?? answer is : ", ex == ex3)
println("dump(ex3):  ") 
dump(ex3) 


私たちはドル記号'$'を使用して、Linux端末と同様に変数の内容を参照できます.

a = 1;
ex4 = :($a + b)   #  $a yields 1, however if a is not yet defined, there will be an error


println("dump(ex4): ")

dump(ex4) 
実行出力

上記のすべてのstuffsで、今ではジュリアでマクロを理解しやすいです.私は、入力として「名前」変数でSayHelloという名前のマクロを定義しようとします.どのように動作するか見てみましょう.
macro sayhello(name)
    return :( println("Hello, ", $name) )
end

@sayhello("jemaloQ")

#=
We can view the quoted return expression using the function macroexpand (important note: this is an extremely useful tool for debugging macros):
=#
ex = macroexpand(Main, :(@sayhello("jemaloQ")) )
println("type of ex: ", typeof(ex), ", ex: ", ex)
eval(ex)
実行出力