[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

• Subject: Memoizing Functions - yet another attempt
• From: Andrew Starks <andrew.starks@...>
• Date: Sat, 14 Dec 2013 16:07:46 -0600

On Saturday, December 14, 2013, Petite Abeille wrote:

On Dec 14, 2013, at 7:53 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:

> Is this a question?

Nah. More of a puzzlement really.

Let take a closer look at that Microlight's memoize function [1]:

(1) It mandates one parameter (not zero, not multiple parameters, just one, not nil, parameter) [2]
(2) It mandates one return value (not zero, not multiple return values, just one, not nil return value) [3]
(3) It prevent parameters from ever being garbage collected

I totally fail to say how such ‘most inflexible solution of all … is the only useful way to do it’.

[1] https://github.com/stevedonovan/Microlight/blob/master/ml.lua#L799
[3] Curiously, the implementation sports varargs, even though they cannot be used in  practice

local k = 0
f = memoize(function( ... ) k = k + 1 return k end)

f()
table index is nil
stack traceback:
TestMem.lua:5: in function '__index'
TestMem.lua:8: in function 'f'
TestMem.lua:16: in main chunk

f( 1 )
f( 1, 2 )
f( 1, 2, 3 )
print( k )

> 1

[3] In fact, if a function happen to return nil it will be evaluated over and over, defeating the entire purpose of the exercise.

local k = 0
f = memoize(function( ... ) k = k + 1 return nil end)

f( 1 )
f( 2 )
f( 3 )
print( k )

> 3

The argument list is:

function(k, ...)

So, it only memoizes on the first argument but accepts many. There must be a general use case for this, but it isn't clear to me what that would be.

Anyone care to edumicate?