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/smog_alado Sep 09 '17 edited Sep 09 '17
It is not a barrier but it is a bit awkward because there is more than one way to do it. (choosing a fixed number of arguments, expanding until receiving nil, etc)
I would argue that this doesn't have to do with varargs actually. A lot of the time, things get much simpler if we use a table argument instead of varargs. :)
Yes, right now Lua is going to create an intermediate closure value if you call
add(a)(b). I think fixing this would require nontrivial changes to the virtual machine to add low-level support for curried functions and a new bytecode that can do the two curried function calls all at once (similar to the concatenation bytecode, which can doa .. b .. cin one step).But those optimizations would only help for cases where currying can be trivially removed, like
add(1)(2), which we might has as well called asadd(1,2)directly. For code that is using lots of higher order combinators (like map, filter, and so on) you need some more aggressive compiler optimizations (such as inlining), which are tricky to do in a highly dynamic scripting language.Functional languages can also have mutable state :)
I probably could have been clearer but the real problem is that the line that calls the curried function doesn't show up in the stack trace.
In the following example, the first line is responsible for the bug but it doesn't show up in the stack trace.
Again, I think the debugability could be improved if the Lua VM were modified to treat curried functions specially and keep track of this info but it would be nontrivial to do so.