[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Better Syntax?
- From: Miroslav Janíček <mira.janicek@...>
- Date: Tue, 4 Oct 2016 19:12:18 +0200
> On 4 Oct 2016, at 17:44, Sean Conner <sean@conman.org> wrote:
>
> It was thus said that the Great Miroslav Janíček once stated:
>>
>>> On 4 Oct 2016, at 0:04, Sean Conner <sean@conman.org> wrote:
>>>
>>> It was thus said that the Great Mike Jones once stated:
>>>> Hi,
>>>>
>>>> I am working on a project where I have basically an event style
>>>> framework, and I would like some way to "chain together" functions.
>>>
>>> I dug through my archives and I found the following bit of code (cleaned
>>> up---I was starting to learn Lua):
>>>
>>> function fappend(f1,f2)
>>> return function(...)
>>> return f2(f1(...))
>>> end
>>> end
>>
>> It might be a good idea to handle cases in which f1 or f2 are undefined:
>
> I disagree [1]. It makes *no* sense to call the function with any of the
> parameters nil (it comes across as pointless) and at worse, it could hide
> bugs in the code elsewhere (why is f1 nil? How could that happen?). [2]
You’re right in that for a general function composition function, this wouldn’t be correct (nil is not the identity function).
However, in this use-case, it might be practical. Suppose we have two modules, module1 and module2.
In module1:
local function foo(...)
-- etc
end
dosomething = fappend(dosomething, foo)
In module2:
local function bar(...)
-- etc
end
dosomething = fappend(dosomething, bar)
Calling dosomething() with both modules loaded would call both foo and bar (in the order in which they were loaded); if we only load one of them, things will still work.
I think something like this is what the OP wanted — but it’s quite likely that I misunderstood the problem!
>> function fappend(f1, f2)
>> if f1 ~= nil and f2 ~= nil then return function(...) return f2(f1(...)) end
>> elseif f1 ~= nil then return f1
>> else return f2
>> end
>> end
>>
>> (And maybe also calling the function “compose” would be more indicative of its intent.)
>
> That I have no problem with.
So in the end, the nil-checking version should not be called “compose”, just the original, proper, composition function (the one you posted). Which is why I kept the name “fappend” in the snippets above.
M.