lua-users home
lua-l archive

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


On Tue, Nov 19, 2013 at 7:17 AM, steve donovan
<steve.j.donovan@gmail.com> wrote:
> I briefly got very excited about the possibilities of doing this, and
> in fact seq.import in PL makes all functions accept seq 'methods'.
> When first experimenting with Microlight I found that composition and
> binding could be very elegantly expressed in the way you describe
> (which feels less ad-hoc than the seq hack).  However, it _is_ a
> global hack.

Slightly OT, but for efficient multi-function composition I use the following:

    cmp_tpl = {1, " = ...; return function(...) return ", 3, "(...", 5, "end"}

    function compose(...)
        local fns, n = {}, select('#', ...)
        if n == 0 then return id end
        for i = 1, n do fns[i] = "f"..i end
        cmp_tpl[1] = table.concat(fns, ", ")
        cmp_tpl[3] = table.concat(fns, "(")
        cmp_tpl[5] = (")"):rep(n)
        return load(t_concat(cmp_tpl))(...) -- or loadstring
    end
    e = compose(f,g,h) --> load("f1, f2, f3 = ...; return
function(...) return f1(f2(f3(...))) end")(f,g,h)

If you're not scared of metaprogramming, feel free to steal it :-).

-- Pierre-Yves