r/lua • u/flappypengujn • Sep 08 '17
Currying in Lua
I'm pretty new to Lua so please excuse any obvious oversights.
- Is there a consensus on the right way to curry an existing function (and I don't mean nested partial applications like
curry(curry(f,1),2), butcurry(f)(1)(2)). Are there any good libraries that do this? - Is there any possibility of curried functions being built into Lua? Or does it conflict with other fundamental language constructs, like varargs or something.
- One particular case that drives me crazy it that it seems really annoying to pass methods around, e.g. as a callback. It’s very easy to carry a function
a.faround, but it seems in order to pass the methoda:fyou have to writefunction(args) a:f(args) end. With currying, this wouldn’t be a problem since a:f would be syntax sugar fora.f(a). This seems to be far more intuitive and (at least to me) the “obvious” way the language should behave. Without currying, is there a simple way around this?
8
Upvotes
View all comments
Show parent comment
1
u/flappypengujn Sep 09 '17
I was hoping there would be a way to avoid defining special curry functions for every case, or passing in the argument length into the function. Now that I think about it though, as you mention that's probably impossible because Lua functions don't have a fixed argument list length.
I agree with what you said, but I'm arguing that a:f should syntactically mean something else instead of
a.f(a, ...). Namely, the following seems sensible to me:should expand to
(where [ ] is a placeholder for code),
and
a:fshould expand toa.f(a).Not only is this way more intuitive (you can use
a:feverywhere in the same way you would usea.f), but it also seems to capture the semantics of methods better: methods are just regular functions that can be "interpreted" as first being bound to an object, then accepting arguments like a normal function. That's exactly when currying should be used.