Is nested function efficient?

后端 未结 5 1340
暖寄归人
暖寄归人 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

    I don't know about lua, but in Scala are very common and used in recursive functions to ensure tail-safe optimization:

    def factorial(i: Int): Int = {
          @tailrec
         def fact(i: Int, accumulator: Int): Int = {
            if (i <= 1)
               accumulator
            else
               fact(i - 1, i * accumulator)
         }
         fact(i, 1)
      }
    

    More info about tail-safe and recursion here

提交回复
热议问题