其输出功能在朱莉娅(Julia)的功能

发布于 2025-02-07 07:42:09 字数 467 浏览 0 评论 0原文

我是朱莉娅用户。 我想定义一个函数,其输出是一个函数。 这是一个例子。

function get_f(p::Int)
    if p == 1
         return f(x) = x^2
    else
         return f(x) = cos(x)
    return f
end

但是它不起作用!

f(x) = get_f(2)
f(2)
# UndefVarError x not defined.

另外,当我运行代码时,我们会发出以下警告。

WARNING: Method definition f(Int64) in module Main at REPL[88]:4

问题是什么?如果您知道另一种好方法,请告诉我。 我想我们可以使用“ struct”编写更复杂的代码,但我不知道如何编写。

I am Julia user.
I want to define a function whose output is a function.
This is an example.

function get_f(p::Int)
    if p == 1
         return f(x) = x^2
    else
         return f(x) = cos(x)
    return f
end

But it does not work!

f(x) = get_f(2)
f(2)
# UndefVarError x not defined.

Also, when I run the code, we have the following WARNING.

WARNING: Method definition f(Int64) in module Main at REPL[88]:4

What is the problem? If you know another good way, please tell me.
I guess we can write more sophisticated code using 'struct', but I don't know how.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋千易 2025-02-14 07:42:09

我们应该使用匿名功能。

function get_f(p::Int)
   if p == 1
        return (x,y) -> x+y
   elseif p == 2
        return (x,y) -> norm(x-y)
   else
        return (x,y) -> x*y
   end
end

f = get_f(2)
f(3,2) # 1.0

有用!

We should use anonymous functions.

function get_f(p::Int)
   if p == 1
        return (x,y) -> x+y
   elseif p == 2
        return (x,y) -> norm(x-y)
   else
        return (x,y) -> x*y
   end
end

f = get_f(2)
f(3,2) # 1.0

It works!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文