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( "tapered" )
local compose = require( "compose" )

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

   return ( a + b ), 1
end

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

   return ( a + b ), 2
end

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

   return ( a + b ), 3
end

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

t.done()

Inspired By

See also