Function 将更新后的函数传递给现有函数

Function 将更新后的函数传递给现有函数,function,julia,Function,Julia,在这个简短的序列中,用户创建了一个函数userfunc(),但随后希望更新第一个定义以执行不同的操作。然而,programfunc()已经编译了第一个版本,并继续使用它 userfunc(str, n) = str ^ n userfunc("hello", 3) "hellohellohello" # program makes use of the user's function programfunc(func, a, b) = func(a, b) programfunc(userf

在这个简短的序列中,用户创建了一个函数
userfunc()
,但随后希望更新第一个定义以执行不同的操作。然而,
programfunc()
已经编译了第一个版本,并继续使用它

userfunc(str, n) = str ^ n
userfunc("hello", 3)

"hellohellohello"

# program makes use of the user's function
programfunc(func, a, b) = func(a, b)
programfunc(userfunc, "hello", 3)

"hellohellohello"

# now the user redefines the function
userfunc(str, n) = str ^ (n * n)
# userfunc("hello", 3) give "hellohellohellohellohellohellohellohellohello"

# but program still makes use of the first userfunc()
programfunc(userfunc, "hello", 3)

"hellohellohello"

那么如何定义
programfunc()
,使其始终使用传递给它的函数的最新定义呢?

invoke
就可以了。(注意,虽然这可能不会编译为nice专用代码)

这里的问题是julia专门研究类型。 也就是说,它为传递给它的每个类型组合编译一个自定义版本的函数。 因为函数在julia 0.5中有一个类型 (每个函数都是单例类型。) 这导致它专门处理函数

在0.5-rc0上测试

julia> userfunc(str, n) = str ^ (n*n)
WARNING: Method definition userfunc(Any, Any) in module Main at REPL[16]:1 overwritten at REPL[20]:1.
userfunc (generic function with 1 method)

julia> function programfunc(func, a, b)
       invoke(func, (typeof(a), typeof(b)), a, b)
       end
programfunc (generic function with 1 method)

julia> programfunc(userfunc, "hello", 3)
"hellohellohellohellohellohellohellohellohello"

julia> userfunc(str, n) = str ^ (n)
WARNING: Method definition userfunc(Any, Any) in module Main at REPL[16]:1 overwritten at REPL[20]:1.
userfunc (generic function with 1 method)

julia> programfunc(userfunc, "hello", 3)
"hellohellohello"
注意,这也适用于


一个简单的解决方法是使用匿名函数:

programfunc((x,y) -> userfunc(x,y), "hello", 3)
这是因为每次都会创建一个新的匿名函数:

julia> f(x) = x
x -> f (generic function with 1 method)

julia> x -> f(x)
(::#15) (generic function with 1 method)

julia> x -> f(x)
(::#17) (generic function with 1 method)

@格尼穆克。啊,这是2011年的265英镑。修正为0.6?谢谢!但是,我如何声明一个函数以便以后接受一个未命名的函数呢?我不理解这个问题。可以将匿名函数作为参数传递给另一个函数,只要传递“普通”函数即可。这就是你要问的吗?换句话说,你没有改变原始函数中的任何内容,而是在你调用它的时候。我想我的意思是,你如何在原始函数定义中指定“传递的”函数参数和类型。例如如何在
函数programfunc(ufunc,a,b)中指定
ufunc
的参数。。。结束
。您不需要在此处指定它们。你使用它就像你最初写的一样。问题是,当您稍后传入匿名函数时;此时,您必须传入足够的参数。(或者做一个splat。)
julia> f(x) = x
x -> f (generic function with 1 method)

julia> x -> f(x)
(::#15) (generic function with 1 method)

julia> x -> f(x)
(::#17) (generic function with 1 method)