munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.75k stars 1.03k forks source link

Way to support function parameter with default value? #1010

Closed Morphlng closed 2 years ago

Morphlng commented 2 years ago

Hi, I want to add default parameter support for Lox function/method, but I'm not sure what is the best way of implementing.

This is what I want:

fun multiply(a, b = 1) {
  return a * b;
}

multiply(5, 2); // 10
multiply(5, 1); // 5
multiply(5);    // 5

How should I store those values, a map with pair like {position : value}? Then how do I call them since I have to check arity() every time I called. Haven't really thought this through, could really appreciate some advice, Thanks!

munificent commented 2 years ago

How should I store those values, a map with pair like {position : value}?

There's no need for a map, since the keys will always be incrementally increasing integers. I'd just do a list of default values for each parameter (with nil as the default default if the function declaration doesn't specify a default).

Then how do I call them since I have to check arity() every time I called.

Yes, in a dynamically typed language, the simplest implementation will have some runtime overhead for checking the arity and filling in any missing arguments with their default.

nocturn9x commented 2 years ago

It's actually easier than you think. In my version I use a tuple that matches 1:1 with the argument list. If the tuple is shorter than the arity of the function, that means that the function has some positional arguments before the keyword ones

Morphlng commented 2 years ago

There's no need for a map, since the keys will always be incrementally increasing integers. I'd just do a list of default values for each parameter (with nil as the default default if the function declaration doesn't specify a default).

Thanks! I also saw other people done that and it's really easy to follow along (even with another language). Now I'm wondering if there is a way to implement function overloading, I can already see ambiguities even before I start coding. I guess that's why Java didn't have them both :)

Anyway, that's all for this issue, thank you all