Is nested function efficient?

后端 未结 5 1344
暖寄归人
暖寄归人 2021-02-12 21:48

In programming languages like Scala or Lua, we can define nested functions such as

function factorial(n)
  function _fac(n, acc)
    if n == 0 then
      return          


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-12 22:19

    Yes (or it used to), as evidenced by Lua's effort to reuse function values when execution passes through a function definition multiple times.

    Lua 5.2 Changes

    Equality between function values has changed. Now, a function definition may not create a new value; it may reuse some previous value if there is no observable difference to the new function.

    Since you have coded (assuming Lua) a function assigned to a global or local declared at a higher scope, you could code the short-circuit yourself (presuming no other code sets it to anything other than nil or false):

    function factorial(n)
      _fac = _fac or function (n, acc)
      …
      end
      …
    end
    

提交回复
热议问题