如何在Julia中从一个函数中使用另一个函数中的表达式。

huangapple go评论98阅读模式
英文:

How to use an expression in function from other function in julia

问题

当我尝试以下代码时:

  1. function f(x)
  2. Meta.parse("x -> x " * x) |> eval
  3. end
  4. function g(x)
  5. findall(Base.invokelatest(f,x),[1,2,3]) |> println
  6. end
  7. g("<3")

Julia会抛出"The applicable method may be too new"错误。

如果我尝试以下代码:

  1. function f(x)
  2. Meta.parse("x -> x " * x) |> eval
  3. end
  4. findall(f("<3"),[1,2,3]) |> println

Julia会给我正确的结果:[1, 2]

如何修改第一个代码片段以在另一个函数中使用字符串生成函数,谢谢!

在Julia 1.6.7中进行测试。

英文:

When I try those code below:

  1. function f(x)
  2. Meta.parse(&quot;x -&gt; x &quot; * x) |&gt; eval
  3. end
  4. function g(x)
  5. findall(Base.invokelatest(f,x),[1,2,3]) |&gt; println
  6. end
  7. g(&quot;&lt;3&quot;)

Julia throws "The applicable method may be too new" error.

If I tried these code below:

  1. function f(x)
  2. Meta.parse(&quot;x -&gt; x &quot; * x) |&gt; eval
  3. end
  4. findall(f(&quot;&lt;3&quot;),[1,2,3]) |&gt; println

Julia could give me corrected result: [1, 2]

How can I modify the first codes to use an String to generate function in other function, Thx!

Test in Julia 1.6.7

答案1

得分: 3

  1. 不同之处在于你的代码中,当你写成:
  2. ```Base.invokelatest(f, x)```
  3. 时,你调用的是 `f`,但 `f` 没有被重新定义。你想要做的是调用由 `f` 返回的函数,而不是 `f` 本身。
英文:

Do

  1. function g(x)
  2. h = f(x)
  3. findall(x -&gt; Base.invokelatest(h, x) ,[1,2,3]) |&gt; println
  4. end
  5. g(&quot;&lt;3&quot;)

The difference in your code is that when you write:

  1. Base.invokelatest(f, x)

you invoke f, but f is not redefined. What you want to do is invokelatest the function that is returned by f instead.

答案2

得分: 1

使用宏而不是函数:

  1. macro f(expr)
  2. Meta.parse("x -> x $expr")
  3. end

现在你可以这样做:

  1. julia> filter(@f("<3"), [1,2,3])
  2. 2-element Vector{Int64}:
  3. 1
  4. 2
英文:

Use a macro instead of function:

  1. macro f(expr)
  2. Meta.parse(&quot;x -&gt; x &quot; * expr)
  3. end

Now you can just do:

  1. julia&gt; filter(@f(&quot;&lt;3&quot;), [1,2,3])
  2. 2-element Vector{Int64}:
  3. 1
  4. 2

huangapple
  • 本文由 发表于 2023年1月9日 15:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定