LoginSignup
2
1

More than 3 years have passed since last update.

文字列を使って関数を定義する

Last updated at Posted at 2020-04-03

やりたいこと

"x + y * sin(z)" のような式(もしくはプログラム)を表す文字列を使って関数を定義したい.
関数名と引数となる変数名はわかっていることにする.
つまり,

name  = "f"
args  = ["x", "y", "z"]
prog  = "x + y * sin(z)"

この3つを使って,

f(x, y, z) = x + y * sin(z)

のような関数定義がやりたい.

バージョンは1.4.0.

実装

nameargsprog から関数を定義する文字列を作って,Meta.parse()してeval()すればOK.
引数部分はjoin()を使ってargsの要素間にコンマを挟んで連結してあげる.

str = "$(name)($(join(args, ","))) = $(prog)"
eval(Meta.parse(str))

実際にやってみるとこんな感じに.

julia> name = "f";

julia> args = ["x", "y", "z"];

julia> prog = "x + y * sin(z)";

julia> str = "$(name)($(join(args, ","))) = $(prog)"
"f(x,y,z) = x + y * sin(z)"

julia> eval(Meta.parse(str))
f (generic function with 1 method)

julia> f(1, 2, π)
1.0000000000000002

julia> f(1, 2, π/2)
3.0
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1