Skip to content

Latest commit

 

History

History
80 lines (64 loc) · 2.07 KB

20.6.md

File metadata and controls

80 lines (64 loc) · 2.07 KB

20.6 コード片を走らせる他の方法

`Code.eval_quated(quated, bindings \ [], opts \ [])

  • quoted: quote が返すような抽象構文木
  • binding: quoted に渡す変数名と値のキーワードリスト
  • opts:
    オプション
    詳細は Code.eval_string/3 参照

指定された抽象構文木を実行する

> fragment = quote do: IO.puts("hello")
{{:., [], [{:__aliases__, [alias: false], [:IO]}, :puts]}, [], ["hello"]}
> Code.eval_quoted fragment
hello
{:ok, []}

バインディングを指定して、quote内からquote外の変数にアクセスする場合

> fragment = quote do: IO.puts(var!(a))
{{:., [], [{:__aliases__, [alias: false], [:IO]}, :puts]}, [],
 [{:var!, [context: Elixir, import: Kernel], [{:a, [], Elixir}]}]}
> Code.eval_quoted fragment, [a: "cat"]
cat
{:ok, [a: "cat"]}

Kernel.var!(var, context \\ nil)

  • var: 参照する変数名
  • context: 変数のコンテキスト

指定された変数を参照する

`Code.string_to_quoted(string, opts \ [])

  • string: quoteされた状態(抽象構文木)に変換するstring
  • opts:
    オプション
    詳細はAPI参照

指定された文字列を抽象構文木に変換する

Macro.to_string(tree, fun)

  • tree: 抽象構文木
  • fun: 抽象構文木の各ノードに適用する関数

指定された抽象構文木を文字列に変換する

> fragment = Code.string_to_quoted("defmodule A do def b(c) do c + 1 end end")
{:ok,
 {:defmodule, [line: 1],
  [
    {:__aliases__, [line: 1], [:A]},
    [
      do: {:def, [line: 1],
       [
         {:b, [line: 1], [{:c, [line: 1], nil}]},
         [do: {:+, [line: 1], [{:c, [line: 1], nil}, 1]}]
       ]}
    ]
  ]}}
> Macro.to_string(fragment)
"{:ok, defmodule(A) do\n  def(b(c)) do\n    c + 1\n  end\nend}"

Code.eval_string(string, binding \\ [], opts \\ [])

  • string: コードの文字列
  • binding: 変数名と値のキーワードリスト
  • opts: オプション

指定された文字列を評価する

> Code.eval_string("[a, a * b, c]", [a: 2, b: 3, c: 4])
{[2, 6, 4], [a: 2, b: 3, c: 4]}