如何根据变量值在函数内部定义函数 [英] How to define a function inside a function depending on variable values

查看:87
本文介绍了如何根据变量值在函数内部定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数,如果它可以根据变量的输入或运行时值不同地定义另一个函数(然后使用该函数),则我会发现它更易于编写和阅读.以下内容说明了这种想法(即使在此简单示例中在函数内部定义函数也没有好处):

I'm writing a function that I would find easier to write and read if it could define another function differently depending on input or runtime values of variables (and then use that function). The following illustrates the idea (even if defining a function inside a function is of no advantage in this simple example):

julia> function f(option::Bool)
           if option
               g() = println("option true")
               g()
           else
               g() = println("option false")
               g()
           end
       end;
WARNING: Method definition g() in module Main at REPL[1]:3 overwritten at REPL[1]:6.

julia> f(true)
option false

julia> f(false)
ERROR: UndefVarError: g not defined
 in f(::Bool) at .\REPL[1]:7

g使用完整的function ... end语法也无济于事.

Using the full function ... end syntax for g does not help either.

问题是:我是否在做错事以得到警告和那种意想不到的行为,或者朱莉娅出于某种原因不允许这样做?如果可以做到,怎么办?

The question is: am I doing something wrong to get that warning and that unintended behavior, or Julia does not allow this for a reason? And if it can be done, how?

对于我目前的需求,我可以定义两个不同的函数g1和g2,它似乎可以工作;但是,如果仅一个任务概念有很多g情况怎么办?我认为一个函数是一流的对象,可以自由操作:分配给一个变量,可以根据条件以某种方式定义,也可以覆盖等.

N.B. For my present need, I can just define two different functions, g1 and g2, and it seems to work; but what if there were many cases of g for just one task concept? I thought that a function, being a first-class object, could be manipulated freely: assigned to a variable, defined in a way or another depending on conditions, overwritten, etc.

P.S.我知道我可以编写一个String然后对其进行解析评估,但这是一个丑陋的解决方案.

P.S. I know I can compose a String and then parse-eval it, but that's an ugly solution.

推荐答案

您要使用匿名函数. 这是一个已知问题(

You want to use anonymous functions. This is a known issue (this other issue also shows your problem).

function f(option::Bool)
           if option
               g = () -> println("option true")
           else
               g = () -> println("option false")
           end
         g
       end

在v0.5中,匿名函数和通用函数之间没有性能差异,因此没有理由不使用匿名函数.请注意,还有一个用于扩展匿名功能的语法:

In v0.5 there's no performance difference between anonymous and generic functions, so there's no reason to not use anonymous functions. Note that there's also a sytnax for extended anonymous functions:

f = function (x)
    x
end

,您可以通过呼叫重载来添加调度:

and you can add dispatches via call overloading:

(T::typeof(f))(x,y) = x+y

所以这里没有理由不使用匿名函数.

so there's no reason to not use an anonymous function here.

这篇关于如何根据变量值在函数内部定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆