partial

function partial( f, ... ) --> mfunc

Description

Takes a function f and fewer than the normal arguments() to f, and returns a function mfunc that takes a variable number of additional arguments. When called, the function mfunc calls f with and the additional arguments.

Parameters

f

The function that should be called.

The arguments of the function f that should be preset.

Return Values

mfunc

A function that calls f with the preset arguments( ).

Code

--ZFUNC-partial-v1
local function partial( f, ... ) --> mfunc
   --ZFUNC-append-v1
   local function append( arr, v, ... )
      table.insert( arr, v )
      if ... then
         for i, o in ipairs{ ... } do
            table.insert( arr, o )
         end
      end
      return arr
   end
   --ZFUNC-unwrap-v1
   local function unwrap( tab, i, j )
      local unpack = unpack or table.unpack
      return unpack( tab, i, j )
   end

   local args = { ... }
   return function( ... )
      return f( unwrap( append( args, ... ) ) )
   end
end

return partial

Examples

local t = require( "tapered" )
local partial = require( "partial" )

local function sum( a, b )
   return a + b
end

fixsum = partial( sum, 100 )

t.is( 128, fixsum( 28 ) )

t.done()

Inspired by

See also