Creating functions with named arguments [message #1044131] |
Thu, 18 April 2013 14:28 |
Erick Fonseca Messages: 68 Registered: December 2011 |
Member |
|
|
I'm trying to define functions which accept named parameters, like in Python. For example:
function f(x, y):
// something
// you can call f like this
f(1, 2)
// or naming the arguments
f(x=1, y=2)
f(y=2, x=1)
f(1, y=2)
// but you can't supply a non named argument after a named one
f(x=1, 2) // wrong
I came up with these rules for the function:
Function:
'function' name=ID '(' parameters+=Parameter (',' parameters+=Parameter)* ')' ':'
statements += Statement+
'end'
;
Parameter:
name = ID
;
FunctionCall:
function=[Function] '(' (paramNames+=[Parameter] '=' )? paramValues+=INT (',' (paramNames+=[Parameter] '=' )? paramValues+=INT )* ')'
;
I also added a ScopeProvider to to provide the parameter names.
Now, how can I enforce the condition that once you give a named parameter in a function call, all subsequent parameters must also be named?
|
|
|
Re: Creating functions with named arguments [message #1044232 is a reply to message #1044131] |
Thu, 18 April 2013 16:43 |
Hallvard Traetteberg Messages: 673 Registered: July 2009 Location: Trondheim, Norway |
Senior Member |
|
|
Some rules/condition are best "enforced" by the validator, not the grammar.
Hallvard
On 18.04.13 07.28, Erick Fonseca wrote:
> I'm trying to define functions which accept named parameters, like in
> Python. For example:
>
>
> function f(x, y):
> // something
>
> // you can call f like this
> f(1, 2)
>
> // or naming the arguments
> f(x=1, y=2)
> f(y=2, x=1)
> f(1, y=2)
>
> // but you can't supply a non named argument after a named one
> f(x=1, 2) // wrong
>
>
>
> I came up with these rules for the function:
>
> Function:
> 'function' name=ID '(' parameters+=Parameter (','
> parameters+=Parameter)* ')' ':'
> statements += Statement+
> 'end'
> ;
>
> Parameter:
> name = ID
> ;
>
> FunctionCall:
> function=[Function] '(' (paramNames+=[Parameter] '=' )?
> paramValues+=INT (',' (paramNames+=[Parameter] '=' )? paramValues+=INT
> )* ')'
> ;
>
>
> I also added a ScopeProvider to to provide the parameter names.
>
> Now, how can I enforce the condition that once you give a named
> parameter in a function call, all subsequent parameters must also be named?
|
|
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.06585 seconds