How do I write a generic memoize function?

后端 未结 15 1712
情话喂你
情话喂你 2020-12-09 05:25

I\'m writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   retu         


        
15条回答
  •  Happy的楠姐
    2020-12-09 06:02

    You're also asking the wrong question for your original problem ;)

    This is a better way for that case:

    triangle(n) = n * (n - 1) / 2

    Furthermore, supposing the formula didn't have such a neat solution, memoisation would still be a poor approach here. You'd be better off just writing a simple loop in this case. See this answer for a fuller discussion.

提交回复
热议问题