lua-users home
lua-l archive

Re: callback implementation details..

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


Am 18.10.03 01:01 schröbte Reuben Thomas:
Did you try this code? I think it is what you might be looking for,
actually. Although you can do it with unpack() etc.
Yes, curry is simply:
-- curry: Partially apply a function
-- f: function to apply partially
-- a1 ... an: arguments to fix
-- returns
-- g: function with ai fixed
function curry (f, ...)
 local fix = arg
 return function (...)
 return f (unpack (fix), unpack (arg))
 end
end
Your version does not work correctly.
If I say
local f = curry( print, 1, 2 )
f( 3, 4 )
I get:
1 3 4
but I should get
1 2 3 4
This is because only the first return value of unpack(fix) is used.
I got that problem with the following helper function:
local function dump( ... )
 io.stdout:write( unpack( arg ), "\n" )
 io.stdout:flush()
end
which only printed the first argument.
For the curry function to work you will need some table merging:
function curry2( f, ... )
 local fix = arg
 return function( ... )
 local params = {}
 for _,a in ipairs( fix ) do
 table.insert( params, a )
 end
 for _,a in ipairs( arg ) do
 table.insert( params, a )
 end
 return f( unpack( params ) )
 end
end
which is a lot simpler than messing around with C.
Philipp

AltStyle によって変換されたページ (->オリジナル) /