compose

function compose( ... ) --> func

Description

Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

Parameters

A variable number of functions that should be composed.

Return Values

func

The composition of the functions.

Code

--ZFUNC-compose-v1
local function compose( ... ) --> func
   --ZFUNC-unwrap-v1
   local function unwrap( tab, i, j )
      local unpack = unpack or table.unpack
      return unpack( tab, i, j )
   end

   local functions = { ... }

   return function( ... )
      local res_arg = { ... }
      for i,f in ipairs( functions ) do
         res_arg = { f( unwrap( res_arg ) ) }
      end
      return unwrap( res_arg )
   end
end

return compose

Examples

local t = require( "taptest" )
local compose = require( "compose" )

local function first( a, b )
   t( a, 1 )
   t( b, 1 )

   return ( a + b ), 1
end

local function second( a, b )
   t( a, 2 )
   t( b, 1 )

   return ( a + b ), 2
end

local function third( a, b )
   t( a, 3 )
   t( b, 2 )

   return ( a + b ), 3
end

local f = compose( first, second, third )
local a, b = f( 1, 1 )
t( a, 5 )
t( b, 3 )

t()

Inspired By

See also