【问题标题】:Pass an updated function to an existing function将更新的函数传递给现有函数
【发布时间】:2016-10-15 10:11:31
【问题描述】:

在这个简短的序列中,用户创建了一个函数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(),使其始终使用传递给它的函数的最新定义?

【问题讨论】:

  • @GnimucK。啊,这是 2011 年的 #265。固定为 0.6?

标签: function julia


【解决方案1】:

invoke 会做到的。 (请注意,虽然这可能不会编译成很好的专用代码)

这里的问题是 julia 专门研究 Type。 也就是说,它为传递给它的每个类型组合编译函数的自定义版本。 由于函数在 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"

注意这也适用于#265

julia> foo(x)=2*x
foo (generic function with 1 method)


julia> function g(x)
       invoke(foo, (typeof(x),), x)
       end
g (generic function with 1 method)

julia> g(2)
4

julia> foo(x)=3*x
WARNING: Method definition foo(Any) in module Main at REPL[1]:1 overwritten at REPL[10]:1.
foo (generic function with 1 method)

julia> g(2)
6

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

    • 谢谢!但是,我如何声明一个函数以稍后接受一个未命名的函数?
    • 我不明白这个问题。您可以将匿名函数作为参数传递给另一个函数,只要您可以传递“普通”函数。你问的是这个吗?
    • 换句话说,你并没有改变原始函数中的任何东西,而是在你调用它的那一刻。
    • 我想我的意思是,你如何在原始函数定义中指定“传递”的函数参数和类型。例如,如何在function programfunc(ufunc, a, b) ... end 中指定ufunc 的参数。
    • 您没有在此处指定它们。你就像你最初写的那样使用它。问题是当你稍后传入匿名函数时;那时你必须传入足够多的参数。 (或者做一个 splat。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2016-06-29
    • 2012-07-23
    • 2013-01-27
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多