Call a function: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 27: | Line 27: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang=11l>F no_args() {} |
||
// call |
// call |
||
no_args() |
no_args() |
||
Line 43: | Line 43: | ||
// calls |
// calls |
||
opt_args() // 1 |
opt_args() // 1 |
||
opt_args(3.141) // 3.141</ |
opt_args(3.141) // 3.141</syntaxhighlight> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Due to assembler, argument are passed by reference.<br> |
Due to assembler, argument are passed by reference.<br> |
||
With: |
With: |
||
< |
<syntaxhighlight lang=360asm>X DS F |
||
Y DS F |
Y DS F |
||
Z DS F</ |
Z DS F</syntaxhighlight> |
||
If you do not want to use the CALL macro instruction and for a link-edited object-module: |
If you do not want to use the CALL macro instruction and for a link-edited object-module: |
||
< |
<syntaxhighlight lang=360asm> L R15,=V(MULTPLIC) |
||
LA R1,PARMLIST address of the paramter list |
LA R1,PARMLIST address of the paramter list |
||
BALR R14,R15 branch and link |
BALR R14,R15 branch and link |
||
Line 58: | Line 58: | ||
* ... |
* ... |
||
PARMLIST DC A(X) |
PARMLIST DC A(X) |
||
DC A(Y)</ |
DC A(Y)</syntaxhighlight> |
||
If you call a link-edited object-module: |
If you call a link-edited object-module: |
||
< |
<syntaxhighlight lang=360asm> CALL MULTPLIC,(X,Y) call MULTPLIC(X,Y) |
||
ST R0,Z Z=MULTPLIC(X,Y)</ |
ST R0,Z Z=MULTPLIC(X,Y)</syntaxhighlight> |
||
If you call an load-module at execution time: |
If you call an load-module at execution time: |
||
< |
<syntaxhighlight lang=360asm> LOAD EP=MULTPLIC load load-module |
||
LR R15,R0 retrieve entry address |
LR R15,R0 retrieve entry address |
||
CALL (R15),(X,Y) call MULTPLIC(X,Y) |
CALL (R15),(X,Y) call MULTPLIC(X,Y) |
||
ST R0,Z Z=MULTPLIC(X,Y)</ |
ST R0,Z Z=MULTPLIC(X,Y)</syntaxhighlight> |
||
=={{header|6502 Assembly}}== |
=={{header|6502 Assembly}}== |
||
Line 72: | Line 72: | ||
To call a function, you use <code>JSR</code> followed by the pointer to its beginning. Most of the time this will be a labeled line of code that your assembler will convert to an actual memory address for you during the assembly process. |
To call a function, you use <code>JSR</code> followed by the pointer to its beginning. Most of the time this will be a labeled line of code that your assembler will convert to an actual memory address for you during the assembly process. |
||
<lang |
<syntaxhighlight lang=6502asm>JSR myFunction</syntaxhighlight> |
||
Function arguments are often passed in through registers, the zero page, or the stack. Given how awkward it is to work with the stack on the 6502, it's best not to use the hardware stack as a means of parameter passing. CC65 uses a software stack in the upper half of zero page, which is indexed using the X register. |
Function arguments are often passed in through registers, the zero page, or the stack. Given how awkward it is to work with the stack on the 6502, it's best not to use the hardware stack as a means of parameter passing. CC65 uses a software stack in the upper half of zero page, which is indexed using the X register. |
||
< |
<syntaxhighlight lang=6502asm>sum: |
||
;adds the values in zero page address $00 and $01, outputs to accumulator. |
;adds the values in zero page address $00 and $01, outputs to accumulator. |
||
LDA $00 ;load the byte stored at memory address $0000 |
LDA $00 ;load the byte stored at memory address $0000 |
||
CLC |
CLC |
||
ADC $01 ;add the byte at memory address $0001 |
ADC $01 ;add the byte at memory address $0001 |
||
RTS ;return</ |
RTS ;return</syntaxhighlight> |
||
The return value is usually stored in the accumulator if it will fit in 8 bits. If not, it's often stored in a dedicated section of the zero page. Since the 6502 has very few registers and all are 8-bit, it's common to set aside a few zero page memory addresses for holding 16-bit return values. |
The return value is usually stored in the accumulator if it will fit in 8 bits. If not, it's often stored in a dedicated section of the zero page. Since the 6502 has very few registers and all are 8-bit, it's common to set aside a few zero page memory addresses for holding 16-bit return values. |
||
Line 91: | Line 91: | ||
To call a function, you use <code>JSR</code> followed by the pointer to its beginning. Most of the time this will be a labeled line of code that your assembler will convert to an actual memory address for you during the assembly process. |
To call a function, you use <code>JSR</code> followed by the pointer to its beginning. Most of the time this will be a labeled line of code that your assembler will convert to an actual memory address for you during the assembly process. |
||
<lang |
<syntaxhighlight lang=68000devpac>JSR myFunction</syntaxhighlight> |
||
Function arguments are often passed in through the stack. When looking at the function in C or a similar language that compiles to 68000 Assembly, the arguments are pushed in the reverse order they are listed. Return values typically go into the D0 register if they're 32-bit or smaller. The CPU does not enforce this, so it's up to the programmer or compiler to use calling conventions to ensure compatibility between software. |
Function arguments are often passed in through the stack. When looking at the function in C or a similar language that compiles to 68000 Assembly, the arguments are pushed in the reverse order they are listed. Return values typically go into the D0 register if they're 32-bit or smaller. The CPU does not enforce this, so it's up to the programmer or compiler to use calling conventions to ensure compatibility between software. |
||
Line 100: | Line 100: | ||
A function that requires no arguments is simply <code>CALL</code>ed: |
A function that requires no arguments is simply <code>CALL</code>ed: |
||
<lang |
<syntaxhighlight lang=asm>call foo</syntaxhighlight> |
||
Functions with a fixed number of arguments have their arguments pushed onto the stack prior to the call. This is how C compilers generate 8086 assembly code. Assembly written by a person can use the stack or registers to pass arguments. Passing via registers is faster but more prone to errors and clobbering, which can cause other functions to not operate correctly. |
Functions with a fixed number of arguments have their arguments pushed onto the stack prior to the call. This is how C compilers generate 8086 assembly code. Assembly written by a person can use the stack or registers to pass arguments. Passing via registers is faster but more prone to errors and clobbering, which can cause other functions to not operate correctly. |
||
< |
<syntaxhighlight lang=asm>push ax ;second argument |
||
push bx ;first argument - typically arguments are pushed in the reverse order they are listed. |
push bx ;first argument - typically arguments are pushed in the reverse order they are listed. |
||
call foo |
call foo |
||
Line 113: | Line 113: | ||
push bp |
push bp |
||
mov bp,sp |
mov bp,sp |
||
;now bp+4 = the value pushed from BX, and bp+6 = the value pushed from AX</ |
;now bp+4 = the value pushed from BX, and bp+6 = the value pushed from AX</syntaxhighlight> |
||
The 8086 cannot support named arguments directly. However it is possible to label a section of RAM, and use that as the argument for a function. |
The 8086 cannot support named arguments directly. However it is possible to label a section of RAM, and use that as the argument for a function. |
||
< |
<syntaxhighlight lang=asm>foo: |
||
ld ax,word ptr[ds:bar] ;load from bar, which is a 16 bit storage location in the data segment (DS), into AX</ |
ld ax,word ptr[ds:bar] ;load from bar, which is a 16 bit storage location in the data segment (DS), into AX</syntaxhighlight> |
||
Built-in functions are typically called using the <code>INT</code> instruction. This instruction takes a numeric constant as its primary argument, and the value in <code>AH</code> as a selector of sorts. This command is used to exit a program and return to MS-DOS: |
Built-in functions are typically called using the <code>INT</code> instruction. This instruction takes a numeric constant as its primary argument, and the value in <code>AH</code> as a selector of sorts. This command is used to exit a program and return to MS-DOS: |
||
< |
<syntaxhighlight lang=asm>mov AH,4Ch |
||
mov AL,00h |
mov AL,00h |
||
int 21h</ |
int 21h</syntaxhighlight> |
||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
< |
<syntaxhighlight lang=AArch64 Assembly> |
||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program callfonct.s */ |
/* program callfonct.s */ |
||
Line 228: | Line 228: | ||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{output}} |
{{output}} |
||
<pre> |
<pre> |
||
Line 238: | Line 238: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang=actionscript> myfunction(); /* function with no arguments in statement context */ |
||
myfunction(6,b); // function with two arguments in statement context |
myfunction(6,b); // function with two arguments in statement context |
||
stringit("apples"); //function with a string argument</ |
stringit("apples"); //function with a string argument</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 250: | Line 250: | ||
* There are no differences between calling built-in vs. user defined functions. |
* There are no differences between calling built-in vs. user defined functions. |
||
* Functions without parameters can be called by omitting the parameter list (no empty brackets!):< |
* Functions without parameters can be called by omitting the parameter list (no empty brackets!):<syntaxhighlight lang=Ada>S: String := Ada.Text_IO.Get_Line;</syntaxhighlight> |
||
* Ada supports functions with optional parameters:< |
* Ada supports functions with optional parameters:<syntaxhighlight lang=Ada>function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional |
||
... |
... |
||
A : Integer := F(12); |
A : Integer := F(12); |
||
B : Integer := F(12, 0); -- the same as A |
B : Integer := F(12, 0); -- the same as A |
||
C : Integer := F(12, 1); -- something different</ |
C : Integer := F(12, 1); -- something different</syntaxhighlight> |
||
* If the number of parameters of F were fixed to two (by omitting the ":= 0" in the specification), then B and C would be OK, but A wouldn't. |
* If the number of parameters of F were fixed to two (by omitting the ":= 0" in the specification), then B and C would be OK, but A wouldn't. |
||
* Ada does not support functions with a variable number of arguments. But a function argument can be an unconstrained array with as many values as you want:< |
* Ada does not support functions with a variable number of arguments. But a function argument can be an unconstrained array with as many values as you want:<syntaxhighlight lang=Ada>type Integer_Array is array (Positive range <>) of Integer; |
||
function Sum(A: Integer_Array) return Integer is |
function Sum(A: Integer_Array) return Integer is |
||
S: Integer := 0; |
S: Integer := 0; |
||
Line 271: | Line 271: | ||
... |
... |
||
A := Sum((1,2,3)); -- A = 6 |
A := Sum((1,2,3)); -- A = 6 |
||
B := Sum((1,2,3,4)); -- B = 10</ |
B := Sum((1,2,3,4)); -- B = 10</syntaxhighlight> |
||
* One can realize first-class functions by defining an access to a function as a parameter:< |
* One can realize first-class functions by defining an access to a function as a parameter:<syntaxhighlight lang=Ada>function H (Int: Integer; |
||
Fun: not null access function (X: Integer; Y: Integer) |
Fun: not null access function (X: Integer; Y: Integer) |
||
return Integer); |
return Integer); |
||
Line 281: | Line 281: | ||
X := H(A, F'Access) -- assuming X and A are Integers, and F is a function |
X := H(A, F'Access) -- assuming X and A are Integers, and F is a function |
||
-- taking two Integers and returning an Integer.</ |
-- taking two Integers and returning an Integer.</syntaxhighlight> |
||
* The caller is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first) < |
* The caller is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first) <syntaxhighlight lang=Ada>Positional := H(A, F'Access); |
||
Named := H(Int => A, Fun => F'Access); |
Named := H(Int => A, Fun => F'Access); |
||
Mixed := H(A, Fun=>F'Access); </ |
Mixed := H(A, Fun=>F'Access); </syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang=algol68># Note functions and subroutines are called procedures (or PROCs) in Algol 68 # |
||
# A function called without arguments: # |
# A function called without arguments: # |
||
f; |
f; |
||
Line 326: | Line 326: | ||
# If the function is declared with argument(s) of mode REF MODE, |
# If the function is declared with argument(s) of mode REF MODE, |
||
then those arguments are being passed by reference. # |
then those arguments are being passed by reference. # |
||
# Technically, all parameters are passed by value, however the value of a REF MODE is a reference... #</ |
# Technically, all parameters are passed by value, however the value of a REF MODE is a reference... #</syntaxhighlight> |
||
See [http://rosettacode.org/wiki/First-class_functions#ALGOL_68 First-Class Functions] for an example of first-class functions in ALGOL 68.<br> |
See [http://rosettacode.org/wiki/First-class_functions#ALGOL_68 First-Class Functions] for an example of first-class functions in ALGOL 68.<br> |
||
Line 334: | Line 334: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang=algolw>% Note, in Algol W, functions are called procedures % |
||
% calling a function with no parameters: % |
% calling a function with no parameters: % |
||
f; |
f; |
||
Line 371: | Line 371: | ||
% parameters are somewhat like macros % |
% parameters are somewhat like macros % |
||
% Partial application is not possible in Algol W %</ |
% Partial application is not possible in Algol W %</syntaxhighlight> |
||
=={{header|AntLang}}== |
=={{header|AntLang}}== |
||
AntLang provides two ways to apply a function. |
AntLang provides two ways to apply a function. |
||
One way is infix application. |
One way is infix application. |
||
<lang |
<syntaxhighlight lang=AntLang>2*2+9</syntaxhighlight> |
||
Infix application is right associative, so x f y g z means x f (y g z) and not (x f y) g z. |
Infix application is right associative, so x f y g z means x f (y g z) and not (x f y) g z. |
||
You can break this rule using parenthesis. |
You can break this rule using parenthesis. |
||
The other way is prefix application. |
The other way is prefix application. |
||
< |
<syntaxhighlight lang=AntLang>*[2;+[2;9]] |
||
echo["Hello!"] |
echo["Hello!"] |
||
time[]</ |
time[]</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
< |
<syntaxhighlight lang=ARM Assembly> |
||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
Line 560: | Line 560: | ||
.Ls_magic_number_10: .word 0x66666667 |
.Ls_magic_number_10: .word 0x66666667 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>printHello: $[][ |
||
print "Hello World!" |
print "Hello World!" |
||
] |
] |
||
Line 599: | Line 599: | ||
print num |
print num |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 614: | Line 614: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang=AHK>; Call a function without arguments: |
||
f() |
f() |
||
Line 653: | Line 653: | ||
; Partial application is impossible. |
; Partial application is impossible. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 659: | Line 659: | ||
The awk interpreter reads the entire script prior to processing, so functions can be called from sections of code appearing before the definition. |
The awk interpreter reads the entire script prior to processing, so functions can be called from sections of code appearing before the definition. |
||
< |
<syntaxhighlight lang=awk>BEGIN { |
||
sayhello() # Call a function with no parameters in statement context |
sayhello() # Call a function with no parameters in statement context |
||
b=squareit(3) # Obtain the return value from a function with a single parameter in first class context |
b=squareit(3) # Obtain the return value from a function with a single parameter in first class context |
||
}</ |
}</syntaxhighlight> |
||
In awk, scalar values are passed by value, but arrays are passed by reference. Note that if a function has no arguments, then empty parentheses are required. |
In awk, scalar values are passed by value, but arrays are passed by reference. Note that if a function has no arguments, then empty parentheses are required. |
||
Line 670: | Line 670: | ||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
In Axe, up to six arguments are passed as the variables r₁ through r₆. As with all variables in Axe, these exist in the global scope, which makes nested function calls and recursion quite difficult. |
In Axe, up to six arguments are passed as the variables r₁ through r₆. As with all variables in Axe, these exist in the global scope, which makes nested function calls and recursion quite difficult. |
||
< |
<syntaxhighlight lang=axe>NOARG() |
||
ARGS(1,5,42)</ |
ARGS(1,5,42)</syntaxhighlight> |
||
Since arguments are simply global variables, they are always optional and can be omitted from right to left. |
Since arguments are simply global variables, they are always optional and can be omitted from right to left. |
||
< |
<syntaxhighlight lang=axe>OPARG(1,2,3,4,5,6) |
||
OPARG(1,2,3) |
OPARG(1,2,3) |
||
OPARG()</ |
OPARG()</syntaxhighlight> |
||
Somewhat similar to [[TI-83 BASIC]], the last evaluated expression becomes the return value of the function. However, this is distinct from the Ans variable. Return values can be captured just like any other expression. |
Somewhat similar to [[TI-83 BASIC]], the last evaluated expression becomes the return value of the function. However, this is distinct from the Ans variable. Return values can be captured just like any other expression. |
||
< |
<syntaxhighlight lang=axe>MATHS(2,4)→A |
||
Disp GETSTR()</ |
Disp GETSTR()</syntaxhighlight> |
||
User-defined functions can be distinguished from language-defined functions by the fact that language-defined function names are composed of atomic tokens (usually with built-in parentheses) whereas user-defined function names are composed of individual characters. Also, because only uppercase letters are available by default in the OS, most user-defined names are all uppercase while language-defined names are mixed case. |
User-defined functions can be distinguished from language-defined functions by the fact that language-defined function names are composed of atomic tokens (usually with built-in parentheses) whereas user-defined function names are composed of individual characters. Also, because only uppercase letters are available by default in the OS, most user-defined names are all uppercase while language-defined names are mixed case. |
||
< |
<syntaxhighlight lang=axe>USER() |
||
axeFunc()</ |
axeFunc()</syntaxhighlight> |
||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang=basic256>function Copialo$ (txt$, siNo, final$) |
||
nuevaCadena$ = "" |
nuevaCadena$ = "" |
||
Line 721: | Line 721: | ||
print |
print |
||
call testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \#incluye texto\#") |
call testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \#incluye texto\#") |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 732: | Line 732: | ||
Batch files do not have a traditional "function" system like OOP languages, however this is the closest thing to it. The only difference between a block of code and a function is the way method you choose to invoke it. It's also worth noting that all batch files can be called from any other batch file, performing a function. A function should be put somewhere in the code where it will not be parsed unless the script is redirected there. |
Batch files do not have a traditional "function" system like OOP languages, however this is the closest thing to it. The only difference between a block of code and a function is the way method you choose to invoke it. It's also worth noting that all batch files can be called from any other batch file, performing a function. A function should be put somewhere in the code where it will not be parsed unless the script is redirected there. |
||
< |
<syntaxhighlight lang=dos> |
||
:: http://rosettacode.org/wiki/Call_a_function |
:: http://rosettacode.org/wiki/Call_a_function |
||
:: Demonstrate the different syntax and semantics provided for calling a function. |
:: Demonstrate the different syntax and semantics provided for calling a function. |
||
Line 819: | Line 819: | ||
endlocal & echo.%filepath%%filename% |
endlocal & echo.%filepath%%filename% |
||
goto:eof |
goto:eof |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 844: | Line 844: | ||
BBC BASIC distinguishes between functions (which return one value), procedures (which may return an arbitrary number of values including zero), and subroutines. Functions can be built-in or user-defined. |
BBC BASIC distinguishes between functions (which return one value), procedures (which may return an arbitrary number of values including zero), and subroutines. Functions can be built-in or user-defined. |
||
A call to a <b>built-in function</b> (for example, the square root function) is an expression: |
A call to a <b>built-in function</b> (for example, the square root function) is an expression: |
||
<lang |
<syntaxhighlight lang=bbcbasic>PRINT SQR(2)</syntaxhighlight> |
||
The parentheses can often be omitted: |
The parentheses can often be omitted: |
||
<lang |
<syntaxhighlight lang=bbcbasic>PRINT SQR 2</syntaxhighlight> |
||
The name of a <b>user-defined function</b> must begin with <tt>FN</tt>. A call to it is also an expression: |
The name of a <b>user-defined function</b> must begin with <tt>FN</tt>. A call to it is also an expression: |
||
< |
<syntaxhighlight lang=bbcbasic>PRINT FN_foo(bar$, baz%)</syntaxhighlight> |
||
(The sigils <tt>$</tt> and <tt>%</tt> identify the variables' types.) |
(The sigils <tt>$</tt> and <tt>%</tt> identify the variables' types.) |
||
A function that takes no arguments can be called omitting the parentheses: |
A function that takes no arguments can be called omitting the parentheses: |
||
<lang |
<syntaxhighlight lang=bbcbasic>PRINT FN_foo</syntaxhighlight> |
||
The name of a <b>procedure</b> must begin with <tt>PROC</tt>. A call to it is a statement, not an expression: |
The name of a <b>procedure</b> must begin with <tt>PROC</tt>. A call to it is a statement, not an expression: |
||
<lang |
<syntaxhighlight lang=bbcbasic>PROC_foo</syntaxhighlight> |
||
If it has arguments, they come in parentheses just as with a function: |
If it has arguments, they come in parentheses just as with a function: |
||
< |
<syntaxhighlight lang=bbcbasic>PROC_foo(bar$, baz%, quux)</syntaxhighlight> |
||
Note that you <i>cannot tell from this syntax</i> which of the variables <tt>bar$</tt>, <tt>baz%</tt>, and <tt>quux</tt> are arguments provided to the procedure and which of them are return values from it. You have to look at where it is defined: |
Note that you <i>cannot tell from this syntax</i> which of the variables <tt>bar$</tt>, <tt>baz%</tt>, and <tt>quux</tt> are arguments provided to the procedure and which of them are return values from it. You have to look at where it is defined: |
||
< |
<syntaxhighlight lang=bbcbasic>DEF PROC_foo(a$, RETURN b%, RETURN c)</syntaxhighlight> |
||
<b>Subroutines</b> are provided for compatibility with older, unstructured dialects of BASIC; otherwise they are never really used. They require statements to be numbered, and they can neither receive arguments nor return values: they can only manipulate global variables. The <tt>GOSUB</tt> and <tt>RETURN</tt> statements in fact mirror assembly language 'jump to subroutine' and 'return from subroutine' instructions quite closely. |
<b>Subroutines</b> are provided for compatibility with older, unstructured dialects of BASIC; otherwise they are never really used. They require statements to be numbered, and they can neither receive arguments nor return values: they can only manipulate global variables. The <tt>GOSUB</tt> and <tt>RETURN</tt> statements in fact mirror assembly language 'jump to subroutine' and 'return from subroutine' instructions quite closely. |
||
<lang |
<syntaxhighlight lang=bbcbasic>200 GOSUB 30050</syntaxhighlight> |
||
Line 869: | Line 869: | ||
'''Calling a function that requires no arguments:''' BQN does not have zero argument functions. Having a function that does so is done with the help of a dummy argument, like so: |
'''Calling a function that requires no arguments:''' BQN does not have zero argument functions. Having a function that does so is done with the help of a dummy argument, like so: |
||
< |
<syntaxhighlight lang=BQN>{𝕊 ·: 1 + 1}0</syntaxhighlight> |
||
The dot symbol <code>·</code> indicates that the argument is nothing, and hence is discarded. Hence, the zero provided to it is discarded, and 1 + 1 = 2 is returned. |
The dot symbol <code>·</code> indicates that the argument is nothing, and hence is discarded. Hence, the zero provided to it is discarded, and 1 + 1 = 2 is returned. |
||
Line 875: | Line 875: | ||
'''Calling a function with a fixed number of arguments:''' BQN functions always take 1 or two arguments, and their names must always start with a capital letter. A function is called like a primitive function, by writing its name or the function itself between the arguments. For example, given a function named <code>F</code>: |
'''Calling a function with a fixed number of arguments:''' BQN functions always take 1 or two arguments, and their names must always start with a capital letter. A function is called like a primitive function, by writing its name or the function itself between the arguments. For example, given a function named <code>F</code>: |
||
<lang |
<syntaxhighlight lang=bqn>F 1</syntaxhighlight> is an example of a single argument call. |
||
<lang |
<syntaxhighlight lang=bqn>2 F 1</syntaxhighlight> is an example of a two argument call. |
||
'''Calling a function with optional arguments:''' optional arguments are not supported by BQN. |
'''Calling a function with optional arguments:''' optional arguments are not supported by BQN. |
||
Line 885: | Line 885: | ||
'''Calling a function with named arguments:''' BQN has block headers, which destructure an input array into given variables using pattern matching. These can then be referenced later by the names given. |
'''Calling a function with named arguments:''' BQN has block headers, which destructure an input array into given variables using pattern matching. These can then be referenced later by the names given. |
||
< |
<syntaxhighlight lang=bqn>{ |
||
𝕊 one‿two‿three: |
𝕊 one‿two‿three: |
||
one∾two∾three |
one∾two∾three |
||
}</ |
}</syntaxhighlight> |
||
Given a three element array, the above example will concatenate them all together. |
Given a three element array, the above example will concatenate them all together. |
||
Line 894: | Line 894: | ||
'''Using a function in statement context:''' BQN user defined functions have the same syntactic roles as primitive functions in an expression, so they can be used like any primitive. |
'''Using a function in statement context:''' BQN user defined functions have the same syntactic roles as primitive functions in an expression, so they can be used like any primitive. |
||
<lang |
<syntaxhighlight lang=bqn>1 {𝕨+𝕩} 2</syntaxhighlight> |
||
is the same as |
is the same as |
||
<lang |
<syntaxhighlight lang=bqn>1 + 2</syntaxhighlight> |
||
'''Using a function in first-class context within an expression:''' BQN supports lisp-style functional programming, and hence supports first class usage of functions. |
'''Using a function in first-class context within an expression:''' BQN supports lisp-style functional programming, and hence supports first class usage of functions. |
||
<lang |
<syntaxhighlight lang=bqn>⟨+, -, ∾⟩</syntaxhighlight> |
||
is an example of a list of functions, which can later be called with the help of a higher order function. |
is an example of a list of functions, which can later be called with the help of a higher order function. |
||
'''Obtaining the return value of a function:''' A block function will always return the value of the last statement within it. To obtain the return value of a function, you can assign it to a variable, or modify an existing variable with the return value. |
'''Obtaining the return value of a function:''' A block function will always return the value of the last statement within it. To obtain the return value of a function, you can assign it to a variable, or modify an existing variable with the return value. |
||
< |
<syntaxhighlight lang=bqn>var ← Func # insert arg here</syntaxhighlight> |
||
Arguments are passed to BQN functions by value only. |
Arguments are passed to BQN functions by value only. |
||
Line 911: | Line 911: | ||
'''Partial Application:''' BQN has two combinators for this purpose. Before (<code>⊸</code>) returns a function with a constant left argument, and After (<code>⟜</code>) returns a function with a constant right argument. |
'''Partial Application:''' BQN has two combinators for this purpose. Before (<code>⊸</code>) returns a function with a constant left argument, and After (<code>⟜</code>) returns a function with a constant right argument. |
||
<lang |
<syntaxhighlight lang=bqn>+⟜2</syntaxhighlight> will add two to the number given to it. |
||
<lang |
<syntaxhighlight lang=bqn>2⊸-</syntaxhighlight> will subtract its input from two. |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
Line 920: | Line 920: | ||
Strictly speaking, all Bracmat functions receive at least one argument. But empty strings are valid expressions, so you can do |
Strictly speaking, all Bracmat functions receive at least one argument. But empty strings are valid expressions, so you can do |
||
<lang |
<syntaxhighlight lang=bracmat>aFunctionWithoutArguments$</syntaxhighlight> |
||
or |
or |
||
<lang |
<syntaxhighlight lang=bracmat>aFunctionWithoutArguments'</syntaxhighlight> |
||
Both function calls pass the right and side of the <code>$</code> or <code>'</code> operator. This is in fact still something: an empty string. |
Both function calls pass the right and side of the <code>$</code> or <code>'</code> operator. This is in fact still something: an empty string. |
||
Line 949: | Line 949: | ||
You can do |
You can do |
||
<lang |
<syntaxhighlight lang=bracmat>func$!myargument;</syntaxhighlight> |
||
The <code>;</code> marks the end of a Bracmat statement. |
The <code>;</code> marks the end of a Bracmat statement. |
||
Line 956: | Line 956: | ||
(Copied from JavaScript:) Bracmat functions are first-class citizens; they can be stored in variables and passed as arguments. Assigning to a variable <code>yourfunc</code> can be done in a few ways. The most common one is |
(Copied from JavaScript:) Bracmat functions are first-class citizens; they can be stored in variables and passed as arguments. Assigning to a variable <code>yourfunc</code> can be done in a few ways. The most common one is |
||
< |
<syntaxhighlight lang=bracmat>(yourfunc=local vars.function body)</syntaxhighlight> |
||
If there is already a function <code>myfunc</code> that you want to assign to <code>yourfunc</code> as well, do |
If there is already a function <code>myfunc</code> that you want to assign to <code>yourfunc</code> as well, do |
||
< |
<syntaxhighlight lang=bracmat>('$myfunc:(=?yourfunc))</syntaxhighlight> |
||
* Obtaining the return value of a function |
* Obtaining the return value of a function |
||
<lang |
<syntaxhighlight lang=bracmat>myfunc$!myarg:?myresult</syntaxhighlight> |
||
Notice that the returned value can be any evaluated expression. |
Notice that the returned value can be any evaluated expression. |
||
Line 974: | Line 974: | ||
You can ignore the return value of a function <code>myfunc</code> as follows: |
You can ignore the return value of a function <code>myfunc</code> as follows: |
||
<lang |
<syntaxhighlight lang=bracmat>myfunc$!myarg&yourfunc$!yourarg</syntaxhighlight> |
||
But notice that if <code>myfunc</code> fails, the above expression returns the value produced by <code>myfunc</code>! To also ignore the success/failure of a function, do |
But notice that if <code>myfunc</code> fails, the above expression returns the value produced by <code>myfunc</code>! To also ignore the success/failure of a function, do |
||
< |
<syntaxhighlight lang=bracmat>`(myfunc$!myarg)&yourfunc$!yourarg</syntaxhighlight> |
||
* Stating whether arguments are passed by value or by reference |
* Stating whether arguments are passed by value or by reference |
||
Line 988: | Line 988: | ||
There is no special syntax for that, but you can write a function that e.g., can take a list with one or with two elements and that returns a function in the first case. |
There is no special syntax for that, but you can write a function that e.g., can take a list with one or with two elements and that returns a function in the first case. |
||
< |
<syntaxhighlight lang=bracmat>( ( plus |
||
= a b |
= a b |
||
. !arg:%?a ?b |
. !arg:%?a ?b |
||
Line 997: | Line 997: | ||
& out$("1+2, not partial:" plus$(1 2)) |
& out$("1+2, not partial:" plus$(1 2)) |
||
& out$("1+2, partial:" (plus$1)$2) |
& out$("1+2, partial:" (plus$1)$2) |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,005: | Line 1,005: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang=c>/* function with no argument */ |
||
f(); |
f(); |
||
Line 1,069: | Line 1,069: | ||
/* Scalar values are passed by value by default. However, arrays are passed by reference. */ |
/* Scalar values are passed by value by default. However, arrays are passed by reference. */ |
||
/* Pointers *sort of* work like references, though. */</ |
/* Pointers *sort of* work like references, though. */</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang=c sharp> |
||
/* a function that has no argument */ |
/* a function that has no argument */ |
||
public int MyFunction(); |
public int MyFunction(); |
||
Line 1,103: | Line 1,103: | ||
public internal MyFunction(); |
public internal MyFunction(); |
||
int returnValue = MyFunction(); |
int returnValue = MyFunction(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang=C++> |
||
/* function with no arguments */ |
/* function with no arguments */ |
||
foo(); |
foo(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=C++> |
||
/* passing arguments by value*/ |
/* passing arguments by value*/ |
||
/* function with one argument */ |
/* function with one argument */ |
||
Line 1,118: | Line 1,118: | ||
/* function with multiple arguments */ |
/* function with multiple arguments */ |
||
baz(arg1, arg2); |
baz(arg1, arg2); |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=C++> |
||
/* get return value of a function */ |
/* get return value of a function */ |
||
variable = function(args); |
variable = function(args); |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=C++> |
||
#include <iostream> |
#include <iostream> |
||
using namespace std; |
using namespace std; |
||
Line 1,140: | Line 1,140: | ||
cout<<"x = "<<x<<endl; /* should produce result "x = 1" */ |
cout<<"x = "<<x<<endl; /* should produce result "x = 1" */ |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang=cobol>CALL "No-Arguments" |
||
*> Fixed number of arguments. |
*> Fixed number of arguments. |
||
Line 1,207: | Line 1,207: | ||
ACCEPT Foo *> Get a PROGRAM-ID from the user. |
ACCEPT Foo *> Get a PROGRAM-ID from the user. |
||
CALL "Use-Func" USING Foo |
CALL "Use-Func" USING Foo |
||
CALL Foo USING Bar</ |
CALL Foo USING Bar</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 1,213: | Line 1,213: | ||
'''Calling a function that requires no arguments''' |
'''Calling a function that requires no arguments''' |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn one [] |
(defn one [] |
||
"Function that takes no arguments and returns 1" |
"Function that takes no arguments and returns 1" |
||
Line 1,219: | Line 1,219: | ||
(one); => 1 |
(one); => 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Calling a function with a fixed number of arguments''' |
'''Calling a function with a fixed number of arguments''' |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn total-cost [item-price num-items] |
(defn total-cost [item-price num-items] |
||
"Returns the total price to buy the given number of items" |
"Returns the total price to buy the given number of items" |
||
Line 1,227: | Line 1,227: | ||
(total-cost 1 5); => 5 |
(total-cost 1 5); => 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Calling a function with optional arguments''' |
'''Calling a function with optional arguments''' |
||
The syntax is exactly the same for the calling code; here's an example of the exact same function as above, except now it takes an optional third argument (discount-percentage) |
The syntax is exactly the same for the calling code; here's an example of the exact same function as above, except now it takes an optional third argument (discount-percentage) |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn total-cost-with-discount [item-price num-items & [discount-percentage]] |
(defn total-cost-with-discount [item-price num-items & [discount-percentage]] |
||
"Returns total price to buy the items after discount is applied (if given)" |
"Returns total price to buy the items after discount is applied (if given)" |
||
Line 1,244: | Line 1,244: | ||
;; Or we can add the third parameter to calculate the cost with 20% discount |
;; Or we can add the third parameter to calculate the cost with 20% discount |
||
(total-cost-with-discount 1 5 20); => 4 |
(total-cost-with-discount 1 5 20); => 4 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Calling a function with a variable number of arguments''' |
'''Calling a function with a variable number of arguments''' |
||
You can use the optional argument syntax seen above to implement variable numbers, but here's another way to do it by writing multiple functions with different arguments all in one. |
You can use the optional argument syntax seen above to implement variable numbers, but here's another way to do it by writing multiple functions with different arguments all in one. |
||
Once again, calling the function is the same, but you need to know what types of arguments are expected for each arity. |
Once again, calling the function is the same, but you need to know what types of arguments are expected for each arity. |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn make-address |
(defn make-address |
||
([city place-name] (str place-name ", " city)) |
([city place-name] (str place-name ", " city)) |
||
Line 1,265: | Line 1,265: | ||
;; Third case |
;; Third case |
||
(make-address "London" "Baker Street" 221 "B"); => "221 Baker Street, Apt. B, London" |
(make-address "London" "Baker Street" 221 "B"); => "221 Baker Street, Apt. B, London" |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Calling a function with named arguments''' |
'''Calling a function with named arguments''' |
||
The way to do this in clojure is to pass the arguments as a map and destructure them by name in the function definition. The syntax is the same, but it requires you to pass a single map argument containing all of your arguments and their names. |
The way to do this in clojure is to pass the arguments as a map and destructure them by name in the function definition. The syntax is the same, but it requires you to pass a single map argument containing all of your arguments and their names. |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn make-mailing-label [{:keys [name address country]}] |
(defn make-mailing-label [{:keys [name address country]}] |
||
"Returns the correct text to mail a letter to the addressee" |
"Returns the correct text to mail a letter to the addressee" |
||
Line 1,281: | Line 1,281: | ||
(make-mailing-label {:name "Her Majesty" |
(make-mailing-label {:name "Her Majesty" |
||
:address "Buckingham Palace, London"}); => "Her Majesty\nBuckingham Palace, London\nUK" |
:address "Buckingham Palace, London"}); => "Her Majesty\nBuckingham Palace, London\nUK" |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Using a function in statement context''' |
'''Using a function in statement context''' |
||
I'm not really sure what this means - you can use a function to assign a variable, but there aren't really statements |
I'm not really sure what this means - you can use a function to assign a variable, but there aren't really statements |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn multiply-by-10 [number] |
(defn multiply-by-10 [number] |
||
(* 10 number)) |
(* 10 number)) |
||
Line 1,291: | Line 1,291: | ||
fifty; => 50 |
fifty; => 50 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Using a function in first-class context within an expression''' |
'''Using a function in first-class context within an expression''' |
||
Line 1,298: | Line 1,298: | ||
You can use one function to create another |
You can use one function to create another |
||
< |
<syntaxhighlight lang=clojure> |
||
(defn make-discount-function [discount-percent] |
(defn make-discount-function [discount-percent] |
||
"Returns a function that takes a price and applies the given discount" |
"Returns a function that takes a price and applies the given discount" |
||
Line 1,316: | Line 1,316: | ||
(discount-50pc 100); => 50 |
(discount-50pc 100); => 50 |
||
(discount-50pc 5); => 2.5 |
(discount-50pc 5); => 2.5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
You can store functions in collections as if they were variables |
You can store functions in collections as if they were variables |
||
< |
<syntaxhighlight lang=clojure> |
||
;; Continuing on the same example, let's imagine Anna has a 20% discount card and Bill has 50%. Charlie pays full price |
;; Continuing on the same example, let's imagine Anna has a 20% discount card and Bill has 50%. Charlie pays full price |
||
;; We can store their discount functions in a map |
;; We can store their discount functions in a map |
||
Line 1,336: | Line 1,336: | ||
(calculate-discounted-price 100 "Bill"); => 50 |
(calculate-discounted-price 100 "Bill"); => 50 |
||
(calculate-discounted-price 100 "Charlie"); => 100 |
(calculate-discounted-price 100 "Charlie"); => 100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
You can pass functions as arguments to other functions |
You can pass functions as arguments to other functions |
||
< |
<syntaxhighlight lang=clojure>;; Here we have two functions to format a price depending on the country |
||
(defn format-price-uk [price] |
(defn format-price-uk [price] |
||
Line 1,357: | Line 1,357: | ||
(format-receipt "Toilet Paper" 5 format-price-us); => "Toilet Paper $5" |
(format-receipt "Toilet Paper" 5 format-price-us); => "Toilet Paper $5" |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Obtaining the return value of a function''' |
'''Obtaining the return value of a function''' |
||
< |
<syntaxhighlight lang=clojure>;;You can assign it to a variable: |
||
(def receipt-us (format-receipt "Toilet Paper" 5 format-price-us)) |
(def receipt-us (format-receipt "Toilet Paper" 5 format-price-us)) |
||
Line 1,374: | Line 1,374: | ||
;; Calls add-store-name with the result of the format function |
;; Calls add-store-name with the result of the format function |
||
(add-store-name (format-receipt "Toilet Paper" 5 format-price-us)); => "Toilet Paper $5\n Thanks for shopping at Safeway" |
(add-store-name (format-receipt "Toilet Paper" 5 format-price-us)); => "Toilet Paper $5\n Thanks for shopping at Safeway" |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Distinguishing built-in functions and user-defined functions''' |
'''Distinguishing built-in functions and user-defined functions''' |
||
< |
<syntaxhighlight lang=clojure>;; They are indistinguishable in Clojure, and you can even override a built in one |
||
;; Using built-in addition |
;; Using built-in addition |
||
Line 1,397: | Line 1,397: | ||
(* 5 5); => 10 |
(* 5 5); => 10 |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Distinguishing subroutines and functions''' |
'''Distinguishing subroutines and functions''' |
||
< |
<syntaxhighlight lang=clojure>;; They are the same thing - indeed, everything in clojure is a function |
||
;; Functions without return values simply return nil |
;; Functions without return values simply return nil |
||
Line 1,406: | Line 1,406: | ||
(no-return-value "hi"); => nil |
(no-return-value "hi"); => nil |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Stating whether arguments are passed by value or by reference''' |
'''Stating whether arguments are passed by value or by reference''' |
||
All data structures are immutable, so they are passed by value only. |
All data structures are immutable, so they are passed by value only. |
||
The value returned from the function does not change the original input |
The value returned from the function does not change the original input |
||
< |
<syntaxhighlight lang=clojure>;; Set up a variable that we will pass to a function |
||
(def the-queen {:name "Elizabeth" |
(def the-queen {:name "Elizabeth" |
||
:title "Your Majesty" |
:title "Your Majesty" |
||
Line 1,427: | Line 1,427: | ||
;; The original data structure is not changed |
;; The original data structure is not changed |
||
the-queen; => {:name "Elizabeth" :title "Your Majesty" :address "Buckingham Palace" :pets ["Corgi" "Horse"]}</ |
the-queen; => {:name "Elizabeth" :title "Your Majesty" :address "Buckingham Palace" :pets ["Corgi" "Horse"]}</syntaxhighlight> |
||
'''Is partial application possible and how''' |
'''Is partial application possible and how''' |
||
Line 1,433: | Line 1,433: | ||
Yes, it is similar to the discount card case we saw earlier. Instead of having a function return another function, we can use partial: |
Yes, it is similar to the discount card case we saw earlier. Instead of having a function return another function, we can use partial: |
||
< |
<syntaxhighlight lang=clojure>(defn apply-discount [discount-percentage price] |
||
"Function to apply a discount to a price" |
"Function to apply a discount to a price" |
||
(-> price |
(-> price |
||
Line 1,450: | Line 1,450: | ||
(discount-10pc-option-2 100); => 90 |
(discount-10pc-option-2 100); => 90 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang=coffeescript> |
||
# Calling a function that requires no arguments |
# Calling a function that requires no arguments |
||
foo() |
foo() |
||
Line 1,505: | Line 1,505: | ||
add2 1 #=> 3 |
add2 1 #=> 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang=lisp> |
||
;Calling a function that requires no arguments |
;Calling a function that requires no arguments |
||
(defun a () "This is the 'A' function") |
(defun a () "This is the 'A' function") |
||
Line 1,534: | Line 1,534: | ||
(apply function (append args-1 args-2)))) |
(apply function (append args-1 args-2)))) |
||
(funcall (curry #'+ 1) 2) |
(funcall (curry #'+ 1) 2) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Cubescript}}== |
=={{header|Cubescript}}== |
||
< |
<syntaxhighlight lang=Cubescript> |
||
// No arguments |
// No arguments |
||
myfunction |
myfunction |
||
Line 1,554: | Line 1,554: | ||
if (strcmp $echo "") [echo builtin function] // true |
if (strcmp $echo "") [echo builtin function] // true |
||
if (strcmp $myfunction "") [echo builtin function] // false |
if (strcmp $myfunction "") [echo builtin function] // false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang=d>import std.traits; |
||
enum isSubroutine(alias F) = is(ReturnType!F == void); |
enum isSubroutine(alias F) = is(ReturnType!F == void); |
||
Line 1,659: | Line 1,659: | ||
alias foo6b = partial!(foo6, 5); |
alias foo6b = partial!(foo6, 5); |
||
assert(foo6b(6) == 11); |
assert(foo6b(6) == 11); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>true |
<pre>true |
||
Line 1,665: | Line 1,665: | ||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang=dart>void main() { |
||
// Function definition |
// Function definition |
||
// See the "Function definition" task for more info |
// See the "Function definition" task for more info |
||
Line 1,694: | Line 1,694: | ||
// Obtaining the return value of a function |
// Obtaining the return value of a function |
||
var value = returnsValue(); |
var value = returnsValue(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Line 1,701: | Line 1,701: | ||
Calling a function without arguments and obtaining its return value: |
Calling a function without arguments and obtaining its return value: |
||
<lang |
<syntaxhighlight lang=delphi>foo()</syntaxhighlight> |
||
Calling a function with optional arguments: |
Calling a function with optional arguments: |
||
<lang |
<syntaxhighlight lang=delphi>foo(1)</syntaxhighlight> |
||
Calling a function with a variable number of arguments: |
Calling a function with a variable number of arguments: |
||
< |
<syntaxhighlight lang=delphi>foo(1, 2, 3, 4, 5)</syntaxhighlight> |
||
Using a function in a statement context: |
Using a function in a statement context: |
||
< |
<syntaxhighlight lang=delphi>writeLn('Hello world.'); |
||
foo; |
foo; |
||
writeLn('Goodbye world')</ |
writeLn('Goodbye world')</syntaxhighlight> |
||
Like above, an empty parameter list, i. e. <tt>()</tt>, could be supplied too. |
Like above, an empty parameter list, i. e. <tt>()</tt>, could be supplied too. |
||
Line 1,715: | Line 1,715: | ||
* Calling a function that requires no arguments |
* Calling a function that requires no arguments |
||
<lang |
<syntaxhighlight lang=dragon>myMethod()</syntaxhighlight> |
||
* Calling a function with a fixed number of arguments |
* Calling a function with a fixed number of arguments |
||
<lang |
<syntaxhighlight lang=dragon>myMethod(97, 3.14)</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
Line 1,724: | Line 1,724: | ||
Calling a function that requires no arguments: |
Calling a function that requires no arguments: |
||
< |
<syntaxhighlight lang=Dyalect>func foo() { } |
||
foo()</ |
foo()</syntaxhighlight> |
||
Calling a function with a fixed number of arguments: |
Calling a function with a fixed number of arguments: |
||
< |
<syntaxhighlight lang=Dyalect>func foo(x, y, z) { } |
||
foo(1, 2, 3)</ |
foo(1, 2, 3)</syntaxhighlight> |
||
Calling a function with optional arguments: |
Calling a function with optional arguments: |
||
< |
<syntaxhighlight lang=Dyalect>func foo(x, y = 0, z = 1) { } |
||
foo(1)</ |
foo(1)</syntaxhighlight> |
||
Calling a function with a variable number of arguments: |
Calling a function with a variable number of arguments: |
||
< |
<syntaxhighlight lang=Dyalect>func foo(args...) { } |
||
foo(1, 2, 3)</ |
foo(1, 2, 3)</syntaxhighlight> |
||
Calling a function with named arguments: |
Calling a function with named arguments: |
||
< |
<syntaxhighlight lang=Dyalect>func foo(x, y, z) { } |
||
foo(z: 3, x: 1, y: 2)</ |
foo(z: 3, x: 1, y: 2)</syntaxhighlight> |
||
Using a function in statement context: |
Using a function in statement context: |
||
< |
<syntaxhighlight lang=Dyalect>func foo() { } |
||
if true { |
if true { |
||
foo() |
foo() |
||
}</ |
}</syntaxhighlight> |
||
Using a function in first-class context within an expression: |
Using a function in first-class context within an expression: |
||
< |
<syntaxhighlight lang=Dyalect>func foo() { } |
||
var x = if foo() { |
var x = if foo() { |
||
1 |
1 |
||
} else { |
} else { |
||
2 |
2 |
||
}</ |
}</syntaxhighlight> |
||
Obtaining the return value of a function: |
Obtaining the return value of a function: |
||
< |
<syntaxhighlight lang=Dyalect>func foo(x) { x * 2 } |
||
var x = 2 |
var x = 2 |
||
var y = foo(x)</ |
var y = foo(x)</syntaxhighlight> |
||
Distinguishing built-in functions and user-defined functions: |
Distinguishing built-in functions and user-defined functions: |
||
< |
<syntaxhighlight lang=Dyalect>//Built-in functions are regular functions from an implicitly imported "lang" module |
||
//There is no actual difference between these functions and user-defined functions |
//There is no actual difference between these functions and user-defined functions |
||
Line 1,781: | Line 1,781: | ||
func foo() { } //A user-defined function |
func foo() { } //A user-defined function |
||
print(isBuiltin(foo)) //Prints: false |
print(isBuiltin(foo)) //Prints: false |
||
print(isBuiltin(assert)) //Prints: true</ |
print(isBuiltin(assert)) //Prints: true</syntaxhighlight> |
||
Distinguishing subroutines and functions: |
Distinguishing subroutines and functions: |
||
< |
<syntaxhighlight lang=Dyalect>//There is no difference between subroutines and functions: |
||
func foo() { } //doesn't explicitly return something (but in fact returns nil) |
func foo() { } //doesn't explicitly return something (but in fact returns nil) |
||
func bar(x) { return x * 2 } //explicitly returns value (keyword "return" can be omitted)</ |
func bar(x) { return x * 2 } //explicitly returns value (keyword "return" can be omitted)</syntaxhighlight> |
||
Stating whether arguments are passed by value or by reference: |
Stating whether arguments are passed by value or by reference: |
||
< |
<syntaxhighlight lang=Dyalect>//All arguments are passed by reference</syntaxhighlight> |
||
Is partial application possible and how: |
Is partial application possible and how: |
||
< |
<syntaxhighlight lang=Dyalect>//Using a closure: |
||
func apply(fun, fst) { snd => fun(fst, snd) } |
func apply(fun, fst) { snd => fun(fst, snd) } |
||
Line 1,809: | Line 1,809: | ||
var sub3 = apply(flip(sub), 3) |
var sub3 = apply(flip(sub), 3) |
||
x = sub3(9) //x is 6</ |
x = sub3(9) //x is 6</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang=dejavu># all functions used are from the standard library |
||
# calling a function with no arguments: |
# calling a function with no arguments: |
||
random-int |
random-int |
||
Line 1,843: | Line 1,843: | ||
# partial application is not possible, due to the fact that |
# partial application is not possible, due to the fact that |
||
# a function's arity is a property of its behavior and not |
# a function's arity is a property of its behavior and not |
||
# of its definition</ |
# of its definition</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.1: |
ELENA 4.1: |
||
Declaring closures |
Declaring closures |
||
< |
<syntaxhighlight lang=elena> |
||
var c0 := { console.writeLine("No argument provided") }; |
var c0 := { console.writeLine("No argument provided") }; |
||
var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") }; |
var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") }; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Calling a closure without arguments |
Calling a closure without arguments |
||
< |
<syntaxhighlight lang=elena> |
||
c0(); |
c0(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Calling a closure with arguments |
Calling a closure with arguments |
||
< |
<syntaxhighlight lang=elena> |
||
c2(2,4); |
c2(2,4); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Passing arguments by reference: |
Passing arguments by reference: |
||
< |
<syntaxhighlight lang=elena> |
||
var exch := (ref object x){ x := 2 }; |
var exch := (ref object x){ x := 2 }; |
||
var a := 1; |
var a := 1; |
||
exch(ref a); |
exch(ref a); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang=elixir> |
||
# Anonymous function |
# Anonymous function |
||
Line 1,927: | Line 1,927: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang=erlang> |
||
no_argument() |
no_argument() |
||
one_argument( Arg ) |
one_argument( Arg ) |
||
Line 1,943: | Line 1,943: | ||
% Arguments are passed by reference, but you can not change them. |
% Arguments are passed by reference, but you can not change them. |
||
% Partial application is possible (a function returns a function that has one argument bound) |
% Partial application is possible (a function returns a function that has one argument bound) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang=fsharp>// No arguments |
||
noArgs() |
noArgs() |
||
Line 1,988: | Line 1,988: | ||
// Partial application example |
// Partial application example |
||
let add2 = (+) 2</ |
let add2 = (+) 2</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
* Calling a word with no arguments: |
* Calling a word with no arguments: |
||
<lang |
<syntaxhighlight lang=Factor>foo</syntaxhighlight> |
||
* Calling a word with a fixed number of arguments. This will pull as many objects as it needs from the stack. If there are not enough, it will result in a stack underflow. |
* Calling a word with a fixed number of arguments. This will pull as many objects as it needs from the stack. If there are not enough, it will result in a stack underflow. |
||
<lang |
<syntaxhighlight lang=Factor>foo</syntaxhighlight> |
||
* No special support for optional arguments. |
* No special support for optional arguments. |
||
* Variable arguments are achieved by defining a word that takes an integer, and operates on that many items at the top of the stack: |
* Variable arguments are achieved by defining a word that takes an integer, and operates on that many items at the top of the stack: |
||
< |
<syntaxhighlight lang=Factor>"a" "b" "c" 3 narray |
||
! { "a" "b" "c" }</ |
! { "a" "b" "c" }</syntaxhighlight> |
||
* The named arguments idiom is to define a tuple, set its slots, and pass it to a word: |
* The named arguments idiom is to define a tuple, set its slots, and pass it to a word: |
||
< |
<syntaxhighlight lang=Factor><email> |
||
"jack@aol.com" >>from |
"jack@aol.com" >>from |
||
{ "jill@aol.com" } >>to |
{ "jill@aol.com" } >>to |
||
"Hello there" >>subject |
"Hello there" >>subject |
||
body >>body |
body >>body |
||
send-email</ |
send-email</syntaxhighlight> |
||
* First-class context: this pushes a word to the stack. Use execute to evaluate. |
* First-class context: this pushes a word to the stack. Use execute to evaluate. |
||
<lang |
<syntaxhighlight lang=Factor>\ foo</syntaxhighlight> |
||
Additionally, you can put words directly inside sequences and quotations for deferred execution: |
Additionally, you can put words directly inside sequences and quotations for deferred execution: |
||
< |
<syntaxhighlight lang=Factor>{ foo } [ foo ]</syntaxhighlight> |
||
* Obtaining the return value, which will be placed on the stack: |
* Obtaining the return value, which will be placed on the stack: |
||
<lang |
<syntaxhighlight lang=Factor>foo</syntaxhighlight> |
||
* Returns true if the word is defined in the Factor VM as opposed to in a vocabulary. It should be noted that there are very few primitives. |
* Returns true if the word is defined in the Factor VM as opposed to in a vocabulary. It should be noted that there are very few primitives. |
||
<lang |
<syntaxhighlight lang=Factor>\ foo primitive?</syntaxhighlight> |
||
* Factor makes no distinction between subroutines and functions. |
* Factor makes no distinction between subroutines and functions. |
||
Line 2,027: | Line 2,027: | ||
* Partial application is possible by use of curry. Here, the object 2 is curried into the left side of the quotation (anonymous function) <tt>[ - ]</tt>: |
* Partial application is possible by use of curry. Here, the object 2 is curried into the left side of the quotation (anonymous function) <tt>[ - ]</tt>: |
||
< |
<syntaxhighlight lang=Factor>{ 1 2 3 } 2 [ - ] curry map . |
||
! { -1 0 1 }</ |
! { -1 0 1 }</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang=forth>a-function \ requiring no arguments |
||
a-function \ with a fixed number of arguents |
a-function \ with a fixed number of arguents |
||
a-function \ having optional arguments |
a-function \ having optional arguments |
||
Line 2,055: | Line 2,055: | ||
: up ( n -- ) negate down ; |
: up ( n -- ) negate down ; |
||
: right ( n -- ) 0 move ; |
: right ( n -- ) 0 move ; |
||
: left ( n -- ) negate right ;</ |
: left ( n -- ) negate right ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
===Examples=== |
===Examples=== |
||
< |
<syntaxhighlight lang=Fortran>program main |
||
implicit none |
implicit none |
||
integer :: a |
integer :: a |
||
Line 2,129: | Line 2,129: | ||
write(*,*) 'Output of subroutine: ', a |
write(*,*) 'Output of subroutine: ', a |
||
end subroutine |
end subroutine |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
Line 2,162: | Line 2,162: | ||
As described in [[Naming_conventions#Fortran|Naming Conventions]], First Fortran (1958) allowed user-written functions but with restrictions on the names so that an ordinary variable called SIN would be disallowed because it was deemed to be in conflict with the library function SINF. These constraints were eased with Fortran II, and the rule became that a user could employ any correct-form name, such as SQRT, for a variable's name (simple or array) but then the library function SQRT would become inaccessible in such a routine. Similarly, there would be no point in the user writing a function called SQRT, because it could not be invoked - the compiler would take any invocation as being for the library routine SQRT. Thus, a user-written function could perhaps chance to have the name of an obscure (i.e. one forgotten about) library function, but if you were lucky it would have conflicting parameters and the compiler will complain. |
As described in [[Naming_conventions#Fortran|Naming Conventions]], First Fortran (1958) allowed user-written functions but with restrictions on the names so that an ordinary variable called SIN would be disallowed because it was deemed to be in conflict with the library function SINF. These constraints were eased with Fortran II, and the rule became that a user could employ any correct-form name, such as SQRT, for a variable's name (simple or array) but then the library function SQRT would become inaccessible in such a routine. Similarly, there would be no point in the user writing a function called SQRT, because it could not be invoked - the compiler would take any invocation as being for the library routine SQRT. Thus, a user-written function could perhaps chance to have the name of an obscure (i.e. one forgotten about) library function, but if you were lucky it would have conflicting parameters and the compiler will complain. |
||
A special case is provided by the "arithmetic statement function" that is defined after declarations but before executable statements in a routine and which has access to all the variables of the routine. Consider < |
A special case is provided by the "arithmetic statement function" that is defined after declarations but before executable statements in a routine and which has access to all the variables of the routine. Consider <syntaxhighlight lang=Fortran> REAL this,that |
||
DIST(X,Y,Z) = SQRT(X**2 + Y**2 + Z**2) + this/that !One arithmetic statement, possibly lengthy. |
DIST(X,Y,Z) = SQRT(X**2 + Y**2 + Z**2) + this/that !One arithmetic statement, possibly lengthy. |
||
... |
... |
||
D = 3 + DIST(X1 - X2,YDIFF,SQRT(ZD2)) !Invoke local function DIST.</ |
D = 3 + DIST(X1 - X2,YDIFF,SQRT(ZD2)) !Invoke local function DIST.</syntaxhighlight> |
||
In this case, even if "DIST" happened to be the name of some library function, invocations within the routine defining it would not be of the library function. |
In this case, even if "DIST" happened to be the name of some library function, invocations within the routine defining it would not be of the library function. |
||
This flexibility in naming can be turned the other way around. For example, some compilers offer the intrinsic function SIND which calculates ''sine'' in degrees. Simply defining an array <code>REAL SIND(0:360)</code> (and properly initialising it) enables the slowish SIND function to be approximated by the faster indexing of an array. Put another way, an array is a function of a limited span of integer-valued arguments and is called in arithmetic expressions with the same syntax as is used for functions, be they intrinsic or user-written. Those writing in Pascal would be blocked by its insistence that arrays employ [] rather than (). Similarly, when testing, an array's declaration might be commented out and a function of that name defined, which function could check its arguments, write to a log file, note time stamps, or whatever else comes to mind. But alas, there is no "palindromic" or reverse-entry facility whereby a function could handle the assignment of a value ''to'' an array that would make this fully flexible. |
This flexibility in naming can be turned the other way around. For example, some compilers offer the intrinsic function SIND which calculates ''sine'' in degrees. Simply defining an array <code>REAL SIND(0:360)</code> (and properly initialising it) enables the slowish SIND function to be approximated by the faster indexing of an array. Put another way, an array is a function of a limited span of integer-valued arguments and is called in arithmetic expressions with the same syntax as is used for functions, be they intrinsic or user-written. Those writing in Pascal would be blocked by its insistence that arrays employ [] rather than (). Similarly, when testing, an array's declaration might be commented out and a function of that name defined, which function could check its arguments, write to a log file, note time stamps, or whatever else comes to mind. But alas, there is no "palindromic" or reverse-entry facility whereby a function could handle the assignment of a value ''to'' an array that would make this fully flexible. |
||
Within a function there are some delicacies. The usual form is to assign the desired result to the name of the variable as in <code>H = A + B</code> where <code>H</code> is the name of the function. However, during evaluation the desired result might be developed over many stages and with reference to prior values. Suppose function H is to combine results from separate statements and it is not convenient to achieve this via one lengthy expression, perhaps because of conditional tests. Something like < |
Within a function there are some delicacies. The usual form is to assign the desired result to the name of the variable as in <code>H = A + B</code> where <code>H</code> is the name of the function. However, during evaluation the desired result might be developed over many stages and with reference to prior values. Suppose function H is to combine results from separate statements and it is not convenient to achieve this via one lengthy expression, perhaps because of conditional tests. Something like <syntaxhighlight lang=Fortran> H = A + B |
||
IF (blah) H = 3*H - 7</ |
IF (blah) H = 3*H - 7</syntaxhighlight> |
||
As written, the appearance of <code>H</code> on the right-hand side of an expression does ''not'' constitute a call of function <code>H</code> at all. Some compilers fail to deal with this as hoped, and so one must use a scratch variable such as <code>FH</code> to develop the value, then remember to ensure that the assignment <code>H = FH</code> is executed before exiting the function, by whatever route. If the result is a large datum (a long character variable, say) this is annoying. |
As written, the appearance of <code>H</code> on the right-hand side of an expression does ''not'' constitute a call of function <code>H</code> at all. Some compilers fail to deal with this as hoped, and so one must use a scratch variable such as <code>FH</code> to develop the value, then remember to ensure that the assignment <code>H = FH</code> is executed before exiting the function, by whatever route. If the result is a large datum (a long character variable, say) this is annoying. |
||
With the belated recognition of recursive possibilities (introduced by Algol in the 1960s) comes the possibility of a function invoking itself. In the above example, <code>H(3.7,5.5,6.6)</code> would clearly be a function invocation (because of the parentheses) whereas <code>H</code> would not be. Actually, Fortran routines have always been able to engage in recursion, it is just the returns that will fail - except on a stack-based system such as the Burroughs 6700 in the 1970s. |
With the belated recognition of recursive possibilities (introduced by Algol in the 1960s) comes the possibility of a function invoking itself. In the above example, <code>H(3.7,5.5,6.6)</code> would clearly be a function invocation (because of the parentheses) whereas <code>H</code> would not be. Actually, Fortran routines have always been able to engage in recursion, it is just the returns that will fail - except on a stack-based system such as the Burroughs 6700 in the 1970s. |
||
Fortran also offers the ability to pass a function as a parameter such that the recipient routine can call it, as in < |
Fortran also offers the ability to pass a function as a parameter such that the recipient routine can call it, as in <syntaxhighlight lang=Fortran> REAL FUNCTION INTG8(F,A,B,DX) !Integrate function F. |
||
EXTERNAL F !Some function of one parameter. |
EXTERNAL F !Some function of one parameter. |
||
REAL A,B !Bounds. |
REAL A,B !Bounds. |
||
Line 2,200: | Line 2,200: | ||
WRITE (6,*) "Result=",INTG8(SIN, 0.0,8*ATAN(1.0),0.01) |
WRITE (6,*) "Result=",INTG8(SIN, 0.0,8*ATAN(1.0),0.01) |
||
WRITE (6,*) "Linear=",INTG8(TRIAL,0.0,1.0, 0.01) |
WRITE (6,*) "Linear=",INTG8(TRIAL,0.0,1.0, 0.01) |
||
END</ |
END</syntaxhighlight> |
||
This involves a fair amount of juggling special declarations so that the compiler will make the desired assumptions that a function is being called upon, rather than the value of some variable. This is eased somewhat with F90 onwards if the MODULE protocol is used so that at least you do not have to remember to declare INTG8 as REAL. Certain library functions are not allowed as candidates for passing to INTG8 (for instance, the compiler may render them as in-line code, bypassing the protocol used for functions) and arithmetic statement functions are usually rejected, as would be an array masquerading as a function. Arithmetic expressions are not allowable as possible "functions" either - how might something like <code>sin(x) + 3*sqrt(x) + 7</code> be recognised as a function instead? As <code>INTG8(SIN + 3*SQRT + 7,''etc...''</code>? Unlike Algol, Fortran does not offer the call-by-name facility as used in [[Jensen's_Device|Jensen's Device]], which would be something like <code>INTG8(SIN(X) + 3*SQRT(X) + 7,''etc...''</code> and would also require passing variable X. Perhaps a keyword BYNAME might be introduced one day. Until then a properly-named function must be declared and its name only be given. And of course, candidate functions must have the correct number and type of parameters, or else... |
This involves a fair amount of juggling special declarations so that the compiler will make the desired assumptions that a function is being called upon, rather than the value of some variable. This is eased somewhat with F90 onwards if the MODULE protocol is used so that at least you do not have to remember to declare INTG8 as REAL. Certain library functions are not allowed as candidates for passing to INTG8 (for instance, the compiler may render them as in-line code, bypassing the protocol used for functions) and arithmetic statement functions are usually rejected, as would be an array masquerading as a function. Arithmetic expressions are not allowable as possible "functions" either - how might something like <code>sin(x) + 3*sqrt(x) + 7</code> be recognised as a function instead? As <code>INTG8(SIN + 3*SQRT + 7,''etc...''</code>? Unlike Algol, Fortran does not offer the call-by-name facility as used in [[Jensen's_Device|Jensen's Device]], which would be something like <code>INTG8(SIN(X) + 3*SQRT(X) + 7,''etc...''</code> and would also require passing variable X. Perhaps a keyword BYNAME might be introduced one day. Until then a properly-named function must be declared and its name only be given. And of course, candidate functions must have the correct number and type of parameters, or else... |
||
This works because Fortran passes parameters by reference (i.e. by giving the machine address of the entity), so that for functions, the code's entry point for the function is passed. With normal variables this means that a function (or subroutine) might modify the value of a parameter, as well as returning the function's result - and also mess with any COMMON data or other available storage, so a function EATACARD(IN) might read a line of data into a shared work area (called say ACARD) from I/O unit number IN and return ''true'', otherwise ''false'' should it hit end-of-file. |
This works because Fortran passes parameters by reference (i.e. by giving the machine address of the entity), so that for functions, the code's entry point for the function is passed. With normal variables this means that a function (or subroutine) might modify the value of a parameter, as well as returning the function's result - and also mess with any COMMON data or other available storage, so a function EATACARD(IN) might read a line of data into a shared work area (called say ACARD) from I/O unit number IN and return ''true'', otherwise ''false'' should it hit end-of-file. |
||
But it is also possible that parameters are passed via copy-in copy-out instead of by reference, with subtle changes in behaviour. This may also be done even on systems that do employ passing by reference. For instance, with < |
But it is also possible that parameters are passed via copy-in copy-out instead of by reference, with subtle changes in behaviour. This may also be done even on systems that do employ passing by reference. For instance, with <syntaxhighlight lang=Fortran> TYPE MIXED |
||
CHARACTER*12 NAME |
CHARACTER*12 NAME |
||
INTEGER STUFF |
INTEGER STUFF |
||
END TYPE MIXED |
END TYPE MIXED |
||
TYPE(MIXED) LOTS(12000)</ |
TYPE(MIXED) LOTS(12000)</syntaxhighlight> |
||
One might hope to try <code>IT = BCHOP(LOTS.NAME,"Fred")</code> where BCHOP is a well-tested function for performing a binary search that should run swiftly. Alas, no. The successive values of NAME are not contiguous while BCHOP expects to receive an array of values that are contiguous - that is, with a "stride" of one. So, the compiler inserts code to copy all the LOTS.NAME elements into such a work area and passes the location of that to BCHOP (which searches it swiftly), then on return, the work area is copied back to LOTS.NAME just in case there had been a change. This latter can be avoided if within BCHOP its array is given the attribute INTENT(IN) for read-only but the incoming copy still means an effort of order N, while for the search the effort is just Log(N). This can have a less-than-subtle effect if large arrays are involved. |
One might hope to try <code>IT = BCHOP(LOTS.NAME,"Fred")</code> where BCHOP is a well-tested function for performing a binary search that should run swiftly. Alas, no. The successive values of NAME are not contiguous while BCHOP expects to receive an array of values that are contiguous - that is, with a "stride" of one. So, the compiler inserts code to copy all the LOTS.NAME elements into such a work area and passes the location of that to BCHOP (which searches it swiftly), then on return, the work area is copied back to LOTS.NAME just in case there had been a change. This latter can be avoided if within BCHOP its array is given the attribute INTENT(IN) for read-only but the incoming copy still means an effort of order N, while for the search the effort is just Log(N). This can have a less-than-subtle effect if large arrays are involved. |
||
=={{header|Fortress}}== |
=={{header|Fortress}}== |
||
< |
<syntaxhighlight lang=fortress> |
||
component call_a_function |
component call_a_function |
||
export Executable |
export Executable |
||
Line 2,252: | Line 2,252: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang=freebasic> |
||
Sub Saludo() |
Sub Saludo() |
||
Print "Hola mundo!" |
Print "Hola mundo!" |
||
Line 2,289: | Line 2,289: | ||
? |
? |
||
testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'") |
testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Hola mundo! |
<pre>Hola mundo! |
||
Line 2,308: | Line 2,308: | ||
'''[https://gambas-playground.proko.eu/?gist=1bbbeb240f6fbca4b893271f1a19833b Click this link to run this code]'''<br> |
'''[https://gambas-playground.proko.eu/?gist=1bbbeb240f6fbca4b893271f1a19833b Click this link to run this code]'''<br> |
||
Some of the uses of Procedures/Functions in Gambas |
Some of the uses of Procedures/Functions in Gambas |
||
< |
<syntaxhighlight lang=gambas>Public Sub Main() |
||
Hello |
Hello |
||
Line 2,332: | Line 2,332: | ||
Print "Hello world!" |
Print "Hello world!" |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,343: | Line 2,343: | ||
The following examples use functions from the standard packages |
The following examples use functions from the standard packages |
||
plus a few dummy local functions: |
plus a few dummy local functions: |
||
::< |
::<syntaxhighlight lang=go>import ( |
||
"image" |
"image" |
||
"image/gif" |
"image/gif" |
||
Line 2,353: | Line 2,353: | ||
func f() (int, float64) { return 0, 0 } |
func f() (int, float64) { return 0, 0 } |
||
func g(int, float64) int { return 0 } |
func g(int, float64) int { return 0 } |
||
func h(string, ...int) {}</ |
func h(string, ...int) {}</syntaxhighlight> |
||
* Calling with no arguments and calling with a fixed number of arguments: |
* Calling with no arguments and calling with a fixed number of arguments: |
||
::< |
::<syntaxhighlight lang=go> f() |
||
g(1, 2.0) |
g(1, 2.0) |
||
// If f() is defined to return exactly the number and type of |
// If f() is defined to return exactly the number and type of |
||
Line 2,363: | Line 2,363: | ||
//h("fail", f()) |
//h("fail", f()) |
||
// But this will: |
// But this will: |
||
g(g(1, 2.0), 3.0)</ |
g(g(1, 2.0), 3.0)</syntaxhighlight> |
||
* Calling with a variable number of arguments: |
* Calling with a variable number of arguments: |
||
::This is only possible with functions defined with a trailing optional/variable length argument of a single type (as <code>h</code> above). < |
::This is only possible with functions defined with a trailing optional/variable length argument of a single type (as <code>h</code> above). <syntaxhighlight lang=go> h("ex1") |
||
h("ex2", 1, 2) |
h("ex2", 1, 2) |
||
h("ex3", 1, 2, 3, 4) |
h("ex3", 1, 2, 3, 4) |
||
Line 2,372: | Line 2,372: | ||
h("ex4", list...) |
h("ex4", list...) |
||
// but again, not mixed with other arguments, this won't compile: |
// but again, not mixed with other arguments, this won't compile: |
||
//h("fail", 2, list...)</ |
//h("fail", 2, list...)</syntaxhighlight> |
||
* Optional arguments and named arguments are not supported. |
* Optional arguments and named arguments are not supported. |
||
::However, it is reasonably common to see a structure used for this. In this example <code>gif.Options</code> is a structure with multiple members which can initialized/assigned by name or omitted (or the whole third argument can just be <code>nil</code>). < |
::However, it is reasonably common to see a structure used for this. In this example <code>gif.Options</code> is a structure with multiple members which can initialized/assigned by name or omitted (or the whole third argument can just be <code>nil</code>). <syntaxhighlight lang=go> gif.Encode(ioutil.Discard, image.Black, &gif.Options{NumColors: 16})</syntaxhighlight> |
||
* Optional arguments are supported. |
* Optional arguments are supported. |
||
::< |
::<syntaxhighlight lang=go>package main |
||
import "fmt" |
import "fmt" |
||
Line 2,389: | Line 2,389: | ||
func main() { |
func main() { |
||
fmt.Println(doIt(Params{a: 1, c: 9})) // prt 10 |
fmt.Println(doIt(Params{a: 1, c: 9})) // prt 10 |
||
}</ |
}</syntaxhighlight> |
||
* Named arguments are supported. |
* Named arguments are supported. |
||
::< |
::<syntaxhighlight lang=go>package main |
||
import "fmt" |
import "fmt" |
||
Line 2,405: | Line 2,405: | ||
args["c"] = 1 |
args["c"] = 1 |
||
bar(args["a"], args["b"], args["c"]) // prt 3, 2, 1 |
bar(args["a"], args["b"], args["c"]) // prt 3, 2, 1 |
||
}</ |
}</syntaxhighlight> |
||
* Within a statement context. |
* Within a statement context. |
||
::Assignment statements are shown later. Only functions returning a single value can be used in a single value context: < |
::Assignment statements are shown later. Only functions returning a single value can be used in a single value context: <syntaxhighlight lang=go> if 2*g(1, 3.0)+4 > 0 {}</syntaxhighlight> |
||
* In a first-class context: |
* In a first-class context: |
||
::< |
::<syntaxhighlight lang=go> fn := func(r rune) rune { |
||
if unicode.IsSpace(r) { |
if unicode.IsSpace(r) { |
||
return -1 |
return -1 |
||
Line 2,417: | Line 2,417: | ||
strings.Map(fn, "Spaces removed") |
strings.Map(fn, "Spaces removed") |
||
strings.Map(unicode.ToLower, "Test") |
strings.Map(unicode.ToLower, "Test") |
||
strings.Map(func(r rune) rune { return r + 1 }, "shift")</ |
strings.Map(func(r rune) rune { return r + 1 }, "shift")</syntaxhighlight> |
||
* Obtaining the value: |
* Obtaining the value: |
||
::<lang> a, b := f() // multivalue return |
::<syntaxhighlight lang=text> a, b := f() // multivalue return |
||
_, c := f() // only some of a multivalue return |
_, c := f() // only some of a multivalue return |
||
d := g(a, c) // single return value |
d := g(a, c) // single return value |
||
e, i := g(d, b), g(d, 2) // multiple assignment</ |
e, i := g(d, b), g(d, 2) // multiple assignment</syntaxhighlight> |
||
* Built-in functions and user defined functions can not be distinguished. |
* Built-in functions and user defined functions can not be distinguished. |
||
::Functions from the standard packages look like any other. The few truly built-in functions are only different in that they have no package specifier like local functions (and they sometimes have extra capabilities). < |
::Functions from the standard packages look like any other. The few truly built-in functions are only different in that they have no package specifier like local functions (and they sometimes have extra capabilities). <syntaxhighlight lang=go> list = append(list, a, d, e, i) |
||
i = len(list)</ |
i = len(list)</syntaxhighlight> |
||
* Go has no subroutines, just functions and methods. |
* Go has no subroutines, just functions and methods. |
||
* Go arguments are passed by value. |
* Go arguments are passed by value. |
||
::As with C, a pointer can be used to achieve the effect of reference passing. (Like pointers, slice arguments have their contents passed by reference, it's the slice header that is passed by value). |
::As with C, a pointer can be used to achieve the effect of reference passing. (Like pointers, slice arguments have their contents passed by reference, it's the slice header that is passed by value). |
||
* Go arguments are passed by value or by reference |
* Go arguments are passed by value or by reference |
||
::< |
::<syntaxhighlight lang=go>package main |
||
import "fmt" |
import "fmt" |
||
Line 2,450: | Line 2,450: | ||
fmt.Println("zeroptr:", i) // prt zeroptr: 0 |
fmt.Println("zeroptr:", i) // prt zeroptr: 0 |
||
fmt.Println("pointer:", &i) // prt pointer: 0xc0000140b8 |
fmt.Println("pointer:", &i) // prt pointer: 0xc0000140b8 |
||
}</ |
}</syntaxhighlight> |
||
* Partial and Currying is not directly supported. |
* Partial and Currying is not directly supported. |
||
::However something similar can be done, see [[Partial function application#Go]] |
::However something similar can be done, see [[Partial function application#Go]] |
||
::< |
::<syntaxhighlight lang=go>package main |
||
import "fmt" |
import "fmt" |
||
Line 2,479: | Line 2,479: | ||
partial := partialSum(13) |
partial := partialSum(13) |
||
fmt.Println(partial(5)) //prt 18 |
fmt.Println(partial(5)) //prt 18 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Line 2,489: | Line 2,489: | ||
* Calling a function that requires no arguments |
* Calling a function that requires no arguments |
||
<lang |
<syntaxhighlight lang=groovy>noArgs()</syntaxhighlight> |
||
* Calling a function with a fixed number of arguments |
* Calling a function with a fixed number of arguments |
||
< |
<syntaxhighlight lang=groovy>fixedArgs(1, "Zing", Color.BLUE, ZonedDateTime.now(), true)</syntaxhighlight> |
||
* Calling a function with optional arguments |
* Calling a function with optional arguments |
||
< |
<syntaxhighlight lang=groovy>optArgs("It's", "a", "beautiful", "day") |
||
optArgs("It's", "a", "beautiful") |
optArgs("It's", "a", "beautiful") |
||
optArgs("It's", "a") |
optArgs("It's", "a") |
||
optArgs("It's")</ |
optArgs("It's")</syntaxhighlight> |
||
* Calling a function with a variable number of arguments |
* Calling a function with a variable number of arguments |
||
< |
<syntaxhighlight lang=groovy>varArgs("It's", "a", "beautiful", "day") |
||
varArgs("It's", "a", "beautiful") |
varArgs("It's", "a", "beautiful") |
||
varArgs("It's", "a") |
varArgs("It's", "a") |
||
varArgs("It's")</ |
varArgs("It's")</syntaxhighlight> |
||
* Calling a function with named arguments |
* Calling a function with named arguments |
||
Line 2,510: | Line 2,510: | ||
* Using a function in statement context |
* Using a function in statement context |
||
< |
<syntaxhighlight lang=groovy>def mean = calcAverage(1.2, 4.5, 3, 8.9, 22, 3)</syntaxhighlight> |
||
* Using a function in first-class context within an expression |
* Using a function in first-class context within an expression |
||
** Create new functions from preexisting functions at run-time |
** Create new functions from preexisting functions at run-time |
||
< |
<syntaxhighlight lang=groovy>def oldFunc = { arg1, arg2 -> arg1 + arg2 } |
||
def newFunc = oldFunc.curry(30) |
def newFunc = oldFunc.curry(30) |
||
assert newFunc(12) == 42</ |
assert newFunc(12) == 42</syntaxhighlight> |
||
** Store functions in collections |
** Store functions in collections |
||
< |
<syntaxhighlight lang=groovy>def funcList = [func1, func2, func3]</syntaxhighlight> |
||
** Use functions as arguments to other functions |
** Use functions as arguments to other functions |
||
< |
<syntaxhighlight lang=groovy>def eltChangeFunc = { it * 3 - 1 } |
||
def changedList = list.collect(eltChangeFunc)</ |
def changedList = list.collect(eltChangeFunc)</syntaxhighlight> |
||
** Use functions as return values of other functions |
** Use functions as return values of other functions |
||
< |
<syntaxhighlight lang=groovy>def funcMaker = { String s, int reps, boolean caps -> |
||
caps ? { String transString -> ((transString + s) * reps).toUpperCase() } |
caps ? { String transString -> ((transString + s) * reps).toUpperCase() } |
||
: { String transString -> (transString + s) * reps } |
: { String transString -> (transString + s) * reps } |
||
} |
} |
||
def func = funcMaker("a", 2, true) |
def func = funcMaker("a", 2, true) |
||
assert func("pook") == "POOKAPOOKA"</ |
assert func("pook") == "POOKAPOOKA"</syntaxhighlight> |
||
* Obtaining the return value of a function |
* Obtaining the return value of a function |
||
< |
<syntaxhighlight lang=groovy>def retVal = func(x, y, z)</syntaxhighlight> |
||
* Distinguishing built-in functions and user-defined functions |
* Distinguishing built-in functions and user-defined functions |
||
Line 2,547: | Line 2,547: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang=haskell> |
||
-- Calling a function with a fixed number of arguments |
-- Calling a function with a fixed number of arguments |
||
multiply x y = x * y |
multiply x y = x * y |
||
Line 2,576: | Line 2,576: | ||
-- Distinguishing subroutines and functions |
-- Distinguishing subroutines and functions |
||
-- Stating whether arguments are passed by value or by reference |
-- Stating whether arguments are passed by value or by reference |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|i}}== |
=={{header|i}}== |
||
< |
<syntaxhighlight lang=i>//The type of the function argument determines whether or not the value is passed by reference or not. |
||
//Eg. numbers are passed by value and lists/arrays are passed by reference. |
//Eg. numbers are passed by value and lists/arrays are passed by reference. |
||
Line 2,607: | Line 2,607: | ||
end |
end |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 2,621: | Line 2,621: | ||
For more information see [[Icon%2BUnicon/Intro|Icon and Unicon Introduction on Rosetta]] |
For more information see [[Icon%2BUnicon/Intro|Icon and Unicon Introduction on Rosetta]] |
||
< |
<syntaxhighlight lang=Icon>procedure main() # demonstrate and describe function calling syntax and semantics |
||
# normal procedure/function calling |
# normal procedure/function calling |
||
Line 2,650: | Line 2,650: | ||
f("x:=",1,"y:=",2) # named parameters (user defined) |
f("x:=",1,"y:=",2) # named parameters (user defined) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 2,658: | Line 2,658: | ||
A verb, in J, typically supports two syntactic variants: |
A verb, in J, typically supports two syntactic variants: |
||
< |
<syntaxhighlight lang=j> verb noun |
||
noun verb noun</ |
noun verb noun</syntaxhighlight> |
||
And a noun, in J, is an array. |
And a noun, in J, is an array. |
||
Line 2,665: | Line 2,665: | ||
An argument list can be represented by an array. Thus, when dealing with multiple arguments, a typical form is: |
An argument list can be represented by an array. Thus, when dealing with multiple arguments, a typical form is: |
||
<lang |
<syntaxhighlight lang=j> function argumentList</syntaxhighlight> |
||
Here, <code>function</code> is a verb and <code>argumentList</code> is a noun. |
Here, <code>function</code> is a verb and <code>argumentList</code> is a noun. |
||
Line 2,671: | Line 2,671: | ||
For example: |
For example: |
||
<lang |
<syntaxhighlight lang=j> sum(1,2,3)</syntaxhighlight> |
||
Here <code>sum</code> is a verb and <code>(1,2,3)</code> is a noun. |
Here <code>sum</code> is a verb and <code>(1,2,3)</code> is a noun. |
||
Line 2,677: | Line 2,677: | ||
Thus: |
Thus: |
||
''A function that requires no arguments'' can be simulated by calling a function with empty argument list: <lang |
''A function that requires no arguments'' can be simulated by calling a function with empty argument list: <syntaxhighlight lang=j>f''</syntaxhighlight> Note that an empty list of characters is not the only constant in the language which is an empty list. That said, most operations in the language do not care what type of data is not present, in an array which contains nothing. |
||
''A function with a fixed number of arguments'' gets special treatment in J when the fixed number is 1 or 2. < |
''A function with a fixed number of arguments'' gets special treatment in J when the fixed number is 1 or 2. <syntaxhighlight lang=j>f 'one argument'</syntaxhighlight>and <syntaxhighlight lang=j>'this example has two arguments' f 'the other argument'</syntaxhighlight> Alternatively, the function can be written such that an argument list is an error when it's the wrong length. |
||
''A function with a variable number of arguments (varargs)'': See above. |
''A function with a variable number of arguments (varargs)'': See above. |
||
If argument types conflict they will need to be put in boxes and the function will have to take its arguments out of the boxes. Here's an unboxed example with five arguments: < |
If argument types conflict they will need to be put in boxes and the function will have to take its arguments out of the boxes. Here's an unboxed example with five arguments: <syntaxhighlight lang=j> f 1,2,3,4,5</syntaxhighlight> and here's a boxed example with five arguments: <syntaxhighlight lang=j>f (<1),(<2),(<3),(<4),(<5) </syntaxhighlight> Note that the last set of parenthesis is unnecessary <syntaxhighlight lang=j>f (<1),(<2),(<3),(<4),<5</syntaxhighlight> Note also that J offers some syntactic sugar for this kind of list <syntaxhighlight lang=j>f 1; 2; 3; 4; <5</syntaxhighlight>. Note also that if the last argument in a semicolon list is not boxed there is no need to explicitly box it, since that is unambiguous (it must be boxed so that it conforms with the other members of the list). <syntaxhighlight lang=j>f 1; 2; 3; 4; 5</syntaxhighlight> |
||
''A function with named arguments'' can be accomplished by calling a function with the names of the arguments. < |
''A function with named arguments'' can be accomplished by calling a function with the names of the arguments. <syntaxhighlight lang=j>f 'george';'tom';'howard'</syntaxhighlight> Other interpretations of this concept are also possible. For example, the right argument for a verb might be a list of argument names and the left argument might be a corresponding list of argument values: <syntaxhighlight lang=j>1 2 3 f 'george';'tom';'howard'</syntaxhighlight> Or, for example a function which requires an object could be thought of as a function with named arguments since an object's members have names:<syntaxhighlight lang=j> obj=: conew'blank' |
||
george__obj=: 1 |
george__obj=: 1 |
||
tom__obj=: 2 |
tom__obj=: 2 |
||
howard__obj=: 3 |
howard__obj=: 3 |
||
f obj |
f obj |
||
coerase obj</ |
coerase obj</syntaxhighlight> Name/value pairs can also be used for this purpose and can be implemented in various ways, including passing names followed by values <syntaxhighlight lang=j>f 'george';1;'tom';2;'howard';3</syntaxhighlight> and passing a structure of pairs <syntaxhighlight lang=j>f ('george';1),('tom';2),:(howard';3)</syntaxhighlight> Or, for example, the pairs could be individually boxed: <syntaxhighlight lang=j>f ('george';1);('tom';2);<howard';3</syntaxhighlight> |
||
''Using a function in command context'' is no different from using a function in any other context, in J. ''Using a function in first class context within an expression'' is no different from using a function in any other context, in J. |
''Using a function in command context'' is no different from using a function in any other context, in J. ''Using a function in first class context within an expression'' is no different from using a function in any other context, in J. |
||
''Obtaining the return value of a function'' is no different from using a function in j. For example, here we add 1 to the result of a function: <lang |
''Obtaining the return value of a function'' is no different from using a function in j. For example, here we add 1 to the result of a function: <syntaxhighlight lang=j>1 + f 2</syntaxhighlight> |
||
The only ''differences that apply to calling builtin functions rather than user defined functions'' is spelling of the function names. |
The only ''differences that apply to calling builtin functions rather than user defined functions'' is spelling of the function names. |
||
Line 2,705: | Line 2,705: | ||
* Calling a function that requires no arguments |
* Calling a function that requires no arguments |
||
<lang |
<syntaxhighlight lang=java>myMethod()</syntaxhighlight> |
||
We didn't specify an object (or a class) as the location of the method, so <tt>this.myMethod()</tt> is assumed. This applies to all the following examples. |
We didn't specify an object (or a class) as the location of the method, so <tt>this.myMethod()</tt> is assumed. This applies to all the following examples. |
||
* Calling a function with a fixed number of arguments |
* Calling a function with a fixed number of arguments |
||
<lang |
<syntaxhighlight lang=java>myMethod(97, 3.14)</syntaxhighlight> |
||
* Calling a function with optional arguments |
* Calling a function with optional arguments |
||
This is possible if the method name is overloaded with different argument lists. For example: |
This is possible if the method name is overloaded with different argument lists. For example: |
||
< |
<syntaxhighlight lang=java>int myMethod(int a, double b){ |
||
// return result of doing sums with a and b |
// return result of doing sums with a and b |
||
} |
} |
||
Line 2,719: | Line 2,719: | ||
int myMethod(int a){ |
int myMethod(int a){ |
||
return f(a, 1.414); |
return f(a, 1.414); |
||
}</ |
}</syntaxhighlight> |
||
The compiler figures out which method to call based on the types of the arguments, so in this case the second argument appears to be optional. If you omit it, the value <tt>1.414</tt> is used. |
The compiler figures out which method to call based on the types of the arguments, so in this case the second argument appears to be optional. If you omit it, the value <tt>1.414</tt> is used. |
||
< |
<syntaxhighlight lang=java>System.out.println( myMethod( 97, 3.14 ) ); |
||
System.out.println( myMethod( 97 ) );</ |
System.out.println( myMethod( 97 ) );</syntaxhighlight> |
||
* Calling a function with a variable number of arguments |
* Calling a function with a variable number of arguments |
||
This is possible if the method is defined with varargs syntax. For example: |
This is possible if the method is defined with varargs syntax. For example: |
||
< |
<syntaxhighlight lang=java>void printAll(String... strings){ |
||
for ( String s : strings ) |
for ( String s : strings ) |
||
System.out.println( s ); |
System.out.println( s ); |
||
}</ |
}</syntaxhighlight> |
||
The type of <tt>strings</tt> is actually a string array, but the caller just passes strings: |
The type of <tt>strings</tt> is actually a string array, but the caller just passes strings: |
||
< |
<syntaxhighlight lang=java>printAll( "Freeman" ); |
||
printAll( "Freeman", "Hardy", "Willis" );</ |
printAll( "Freeman", "Hardy", "Willis" );</syntaxhighlight> |
||
To avoid ambiguity, only the last argument to a function can have varargs. |
To avoid ambiguity, only the last argument to a function can have varargs. |
||
Line 2,740: | Line 2,740: | ||
* Calling a function with named arguments |
* Calling a function with named arguments |
||
Not directly possible, but you could simulate this (somewhat verbosely): |
Not directly possible, but you could simulate this (somewhat verbosely): |
||
< |
<syntaxhighlight lang=java>int myMethod( Map<String,Object> params ){ |
||
return |
return |
||
((Integer)params.get("x")).intValue() |
((Integer)params.get("x")).intValue() |
||
+ ((Integer)params.get("y")).intValue(); |
+ ((Integer)params.get("y")).intValue(); |
||
}</ |
}</syntaxhighlight> |
||
Called like this: |
Called like this: |
||
< |
<syntaxhighlight lang=java>System.out.println( myMethod(new HashMap<String,Object>(){{put("x",27);put("y",52);}}) );</syntaxhighlight> |
||
Yuk. |
Yuk. |
||
Line 2,758: | Line 2,758: | ||
* Obtaining the return value of a function |
* Obtaining the return value of a function |
||
< |
<syntaxhighlight lang=java>int i = myMethod(x);</syntaxhighlight> |
||
* Distinguishing built-in functions and user-defined functions |
* Distinguishing built-in functions and user-defined functions |
||
Line 2,768: | Line 2,768: | ||
* Stating whether arguments are passed by value or by reference |
* Stating whether arguments are passed by value or by reference |
||
All arguments are passed by value, but since object variables contain a reference to an object (not the object itself), objects appear to be passed by reference. For example: |
All arguments are passed by value, but since object variables contain a reference to an object (not the object itself), objects appear to be passed by reference. For example: |
||
< |
<syntaxhighlight lang=java>myMethod(List<String> list){ |
||
// If I change the contents of the list here, the caller will see the change |
// If I change the contents of the list here, the caller will see the change |
||
}</ |
}</syntaxhighlight> |
||
* Is partial application possible and how |
* Is partial application possible and how |
||
Line 2,779: | Line 2,779: | ||
The arguments to a JavaScript function are stored in a special array-like object which does not enforce arity in any way; a function declared to take ''n'' arguments may be called with none‒and vice versa‒without raising an error. |
The arguments to a JavaScript function are stored in a special array-like object which does not enforce arity in any way; a function declared to take ''n'' arguments may be called with none‒and vice versa‒without raising an error. |
||
< |
<syntaxhighlight lang=JavaScript>var foo = function() { return arguments.length }; |
||
foo() // 0 |
foo() // 0 |
||
foo(1, 2, 3) // 3</ |
foo(1, 2, 3) // 3</syntaxhighlight> |
||
Neither optional (see above) nor named arguments are supported, though the latter (and the inverse of the former) may be simulated with the use of a helper object to be queried for the existence and/or values of relevant keys. <span style="color: transparent;">Seriously, what is "statement context"?</span> |
Neither optional (see above) nor named arguments are supported, though the latter (and the inverse of the former) may be simulated with the use of a helper object to be queried for the existence and/or values of relevant keys. <span style="color: transparent;">Seriously, what is "statement context"?</span> |
||
JavaScript functions are first-class citizens; they can be stored in variables (see above) and passed as arguments. |
JavaScript functions are first-class citizens; they can be stored in variables (see above) and passed as arguments. |
||
< |
<syntaxhighlight lang=JavaScript>var squares = [1, 2, 3].map(function (n) { return n * n }); // [1, 4, 9]</syntaxhighlight> |
||
Naturally, they can also be returned, thus partial application is supported. |
Naturally, they can also be returned, thus partial application is supported. |
||
< |
<syntaxhighlight lang=JavaScript> |
||
var make_adder = function(m) { |
var make_adder = function(m) { |
||
return function(n) { return m + n } |
return function(n) { return m + n } |
||
}; |
}; |
||
var add42 = make_adder(42); |
var add42 = make_adder(42); |
||
add42(10) // 52</ |
add42(10) // 52</syntaxhighlight> |
||
Calling a user-defined function's <tt>toString()</tt> method returns its source verbatim; that the implementation is elided for built-ins provides a mechanism for distinguishing between the two. |
Calling a user-defined function's <tt>toString()</tt> method returns its source verbatim; that the implementation is elided for built-ins provides a mechanism for distinguishing between the two. |
||
< |
<syntaxhighlight lang=JavaScript>foo.toString() |
||
"function () { return arguments.length }" |
"function () { return arguments.length }" |
||
alert.toString() |
alert.toString() |
||
"function alert() { [native code] }"</ |
"function alert() { [native code] }"</syntaxhighlight> |
||
Arguments are passed by value, but the members of collections are essentially passed by reference and thus propagate modification. |
Arguments are passed by value, but the members of collections are essentially passed by reference and thus propagate modification. |
||
< |
<syntaxhighlight lang=JavaScript>var mutate = function(victim) { |
||
victim[0] = null; |
victim[0] = null; |
||
victim = 42; |
victim = 42; |
||
}; |
}; |
||
var foo = [1, 2, 3]; |
var foo = [1, 2, 3]; |
||
mutate(foo) // foo is now [null, 2, 3], not 42</ |
mutate(foo) // foo is now [null, 2, 3], not 42</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 2,877: | Line 2,877: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang=Julia> |
||
# Calling a function that requires no arguments: |
# Calling a function that requires no arguments: |
||
f() = print("Hello world!") |
f() = print("Hello world!") |
||
Line 2,968: | Line 2,968: | ||
v = [4, 6, 8] |
v = [4, 6, 8] |
||
map(x -> f(x, 10), v) # v = [30, 52, 82] |
map(x -> f(x, 10), v) # v = [30, 52, 82] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
In Kotlin parameters are always passed by value though, apart from the (unboxed) primitive types, the value passed is actually a reference to an object. |
In Kotlin parameters are always passed by value though, apart from the (unboxed) primitive types, the value passed is actually a reference to an object. |
||
< |
<syntaxhighlight lang=scala>// version 1.0.6 |
||
fun fun1() = println("No arguments") |
fun fun1() = println("No arguments") |
||
Line 3,004: | Line 3,004: | ||
println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit) |
println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit) |
||
println(fun8("Hello")("world")) // partial application isn't supported though you can do this |
println(fun8("Hello")("world")) // partial application isn't supported though you can do this |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,024: | Line 3,024: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
In lambdatalk functions are abstractions {lambda {args} body} whose behaviour is best explained as a part of such a complete expression {{lambda {args} body} values}. |
In lambdatalk functions are abstractions {lambda {args} body} whose behaviour is best explained as a part of such a complete expression {{lambda {args} body} values}. |
||
< |
<syntaxhighlight lang=scheme> |
||
The command |
The command |
||
Line 3,073: | Line 3,073: | ||
More can be seen in http://lambdaway.free.fr/lambdawalks/?view=lambda |
More can be seen in http://lambdaway.free.fr/lambdawalks/?view=lambda |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 3,083: | Line 3,083: | ||
=== parentheses === |
=== parentheses === |
||
< |
<syntaxhighlight lang=langur>.x() |
||
# call user-defined function</ |
# call user-defined function</syntaxhighlight> |
||
< |
<syntaxhighlight lang=langur>write(.key, ": ", .value) |
||
# call built-in with parentheses</ |
# call built-in with parentheses</syntaxhighlight> |
||
=== unbounded lists === |
=== unbounded lists === |
||
< |
<syntaxhighlight lang=langur>write .key, ": ", .value |
||
# call built-in with unbounded list</ |
# call built-in with unbounded list</syntaxhighlight> |
||
< |
<syntaxhighlight lang=langur>writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4] |
||
# unbounded lists on writeln and join |
# unbounded lists on writeln and join |
||
# later function join takes remaining arguments</ |
# later function join takes remaining arguments</syntaxhighlight> |
||
< |
<syntaxhighlight lang=langur>writeln "numbers: ", join(", ", [.a1, .a2, .a3, .a4]), " === " |
||
# unbounded list on writeln |
# unbounded list on writeln |
||
# join using parentheses so it doesn't take remaining arguments</ |
# join using parentheses so it doesn't take remaining arguments</syntaxhighlight> |
||
< |
<syntaxhighlight lang=langur>val .sum = foldfrom( |
||
f(.sum, .i, .c) .sum + toNumber(.c, 36) x .weight[.i], |
f(.sum, .i, .c) .sum + toNumber(.c, 36) x .weight[.i], |
||
0, |
0, |
||
Line 3,107: | Line 3,107: | ||
split ZLS, .code, |
split ZLS, .code, |
||
) |
) |
||
# split, pseries, and len using unbounded lists, ending before comma preceding line return</ |
# split, pseries, and len using unbounded lists, ending before comma preceding line return</syntaxhighlight> |
||
< |
<syntaxhighlight lang=langur>for .key in sort(keys .tests) { |
||
... |
... |
||
} |
} |
||
# unbounded list on keys bounded by closing parenthesis of sort</ |
# unbounded list on keys bounded by closing parenthesis of sort</syntaxhighlight> |
||
=={{header|Latitude}}== |
=={{header|Latitude}}== |
||
Line 3,118: | Line 3,118: | ||
Like Ruby, Latitude doesn't have functions in the traditional sense, only methods. Methods can be called with parentheses, as in many languages. If a method takes no arguments, the parentheses may be omitted. If a method takes a single argument and that argument is a literal (such as a literal number or string), then the parentheses may also be omitted. Additionally, Latitude provides an alternative syntax for method calls which replaces the parentheses with a colon. |
Like Ruby, Latitude doesn't have functions in the traditional sense, only methods. Methods can be called with parentheses, as in many languages. If a method takes no arguments, the parentheses may be omitted. If a method takes a single argument and that argument is a literal (such as a literal number or string), then the parentheses may also be omitted. Additionally, Latitude provides an alternative syntax for method calls which replaces the parentheses with a colon. |
||
<lang>foo (1, 2, 3). ; (1) Ordinary call |
<syntaxhighlight lang=text>foo (1, 2, 3). ; (1) Ordinary call |
||
foo (). ; (2) No arguments |
foo (). ; (2) No arguments |
||
foo. ; (3) Equivalent to (2) |
foo. ; (3) Equivalent to (2) |
||
Line 3,124: | Line 3,124: | ||
foo 1. ; (5) Equivalent to (4) |
foo 1. ; (5) Equivalent to (4) |
||
foo (bar). ; (6) Parentheses necessary here since bar is not a literal |
foo (bar). ; (6) Parentheses necessary here since bar is not a literal |
||
foo: 1, 2, 3. ; (7) Alternative syntax, equivalent to (1)</ |
foo: 1, 2, 3. ; (7) Alternative syntax, equivalent to (1)</syntaxhighlight> |
||
Although methods themselves can be passed around as first-class values, the method evaluation semantics often make such an approach suboptimal. If one needs a first-class function in the traditional sense, the usual approach is to wrap it in a <code>Proc</code> object and then call it explicitly as needed. |
Although methods themselves can be passed around as first-class values, the method evaluation semantics often make such an approach suboptimal. If one needs a first-class function in the traditional sense, the usual approach is to wrap it in a <code>Proc</code> object and then call it explicitly as needed. |
||
<lang>myProc := proc { foo. }. |
<syntaxhighlight lang=text>myProc := proc { foo. }. |
||
myProc call (1, 2, 3).</ |
myProc call (1, 2, 3).</syntaxhighlight> |
||
If you want to write a function which can accept either a <code>Proc</code> or a method object (as many standard library functions do, for convenience), you may use the <code>shield</code> method to ensure that the object is a <code>Proc</code>. <code>shield</code> wraps methods in a <code>Proc</code> while leaving objects which are already procedures alone. |
If you want to write a function which can accept either a <code>Proc</code> or a method object (as many standard library functions do, for convenience), you may use the <code>shield</code> method to ensure that the object is a <code>Proc</code>. <code>shield</code> wraps methods in a <code>Proc</code> while leaving objects which are already procedures alone. |
||
<lang>myProc1 := #'foo shield. |
<syntaxhighlight lang=text>myProc1 := #'foo shield. |
||
myProc2 := proc { foo. }. |
myProc2 := proc { foo. }. |
||
myProc3 := proc { foo. } shield.</ |
myProc3 := proc { foo. } shield.</syntaxhighlight> |
||
All three of the above procedures will act the same. |
All three of the above procedures will act the same. |
||
Line 3,144: | Line 3,144: | ||
In some module, define the following: |
In some module, define the following: |
||
< |
<syntaxhighlight lang=lisp> |
||
(defun my-func() |
(defun my-func() |
||
(: io format '"I get called with NOTHING!~n")) |
(: io format '"I get called with NOTHING!~n")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Then you use it like so (depending upon how you import it): |
Then you use it like so (depending upon how you import it): |
||
< |
<syntaxhighlight lang=lisp> |
||
> (my-func) |
> (my-func) |
||
I get called with NOTHING! |
I get called with NOTHING! |
||
ok |
ok |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Calling a function with a fixed number of arguments:''' |
'''Calling a function with a fixed number of arguments:''' |
||
In some module, define the following: |
In some module, define the following: |
||
< |
<syntaxhighlight lang=lisp> |
||
(defun my-func(a b) |
(defun my-func(a b) |
||
(: io format '"I got called with ~p and ~p~n" (list a b))) |
(: io format '"I got called with ~p and ~p~n" (list a b))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Then you use it like so: |
Then you use it like so: |
||
< |
<syntaxhighlight lang=lisp> |
||
> (my-func '"bread" '"cheese") |
> (my-func '"bread" '"cheese") |
||
I got called with "bread" and "cheese" |
I got called with "bread" and "cheese" |
||
ok |
ok |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Calling a function with optional arguments or calling a function with a variable number of arguments:''' |
'''Calling a function with optional arguments or calling a function with a variable number of arguments:''' |
||
Line 3,176: | Line 3,176: | ||
* One can define multiple functions so that it ''appears'' that one is calling a function with optional or a variable number of arguments: |
* One can define multiple functions so that it ''appears'' that one is calling a function with optional or a variable number of arguments: |
||
< |
<syntaxhighlight lang=lisp> |
||
(defmodule args |
(defmodule args |
||
(export all)) |
(export all)) |
||
Line 3,191: | Line 3,191: | ||
(defun my-func (a b c) |
(defun my-func (a b c) |
||
(: io format '"~p ~p ~p~n" (list a b c))) |
(: io format '"~p ~p ~p~n" (list a b c))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Here is some example usage: |
Here is some example usage: |
||
< |
<syntaxhighlight lang=lisp> |
||
> (slurp '"args.lfe") |
> (slurp '"args.lfe") |
||
#(ok args) |
#(ok args) |
||
Line 3,211: | Line 3,211: | ||
> (my-func '"apple" '"banana" '"cranberry" '"bad arg") |
> (my-func '"apple" '"banana" '"cranberry" '"bad arg") |
||
exception error: #(unbound_func #(my-func 4)) |
exception error: #(unbound_func #(my-func 4)) |
||
</ |
</syntaxhighlight> |
||
'''Calling a function with named arguments:''' |
'''Calling a function with named arguments:''' |
||
Line 3,221: | Line 3,221: | ||
'''Using a function in statement context:''' |
'''Using a function in statement context:''' |
||
< |
<syntaxhighlight lang=lisp> |
||
... |
... |
||
(cond ((== count limit) (hit-limit-func arg-1 arg-2)) |
(cond ((== count limit) (hit-limit-func arg-1 arg-2)) |
||
((/= count limit) (keep-going-func count))) |
((/= count limit) (keep-going-func count))) |
||
... |
... |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Using a function in first-class context within an expression:''' |
'''Using a function in first-class context within an expression:''' |
||
From the LFE REPL: |
From the LFE REPL: |
||
< |
<syntaxhighlight lang=lisp> |
||
> (>= 0.5 (: math sin 0.5)) |
> (>= 0.5 (: math sin 0.5)) |
||
true |
true |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Obtaining the return value of a function:''' |
'''Obtaining the return value of a function:''' |
||
There are many, many ways to assign function outputs to variables in LFE. One fairly standard way is with the <code>(let ...)</code> form: |
There are many, many ways to assign function outputs to variables in LFE. One fairly standard way is with the <code>(let ...)</code> form: |
||
< |
<syntaxhighlight lang=lisp> |
||
(let ((x (: math sin 0.5))) |
(let ((x (: math sin 0.5))) |
||
...) |
...) |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Distinguishing built-in functions and user-defined functions:''' |
'''Distinguishing built-in functions and user-defined functions:''' |
||
Line 3,269: | Line 3,269: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang=lb> |
|||
<lang lb> |
|||
'Call a function - Liberty BASIC |
'Call a function - Liberty BASIC |
||
Line 3,312: | Line 3,312: | ||
'Is partial application possible and how |
'Is partial application possible and how |
||
'impossible |
'impossible |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
*Calling a function that requires no arguments |
*Calling a function that requires no arguments |
||
< |
<syntaxhighlight lang=lingo>foo() |
||
-- or alternatively: |
-- or alternatively: |
||
call(#foo, _movie)</ |
call(#foo, _movie)</syntaxhighlight> |
||
*Calling a function with a fixed number of arguments |
*Calling a function with a fixed number of arguments |
||
< |
<syntaxhighlight lang=lingo>foo(1,2,3) |
||
-- or alternatively: |
-- or alternatively: |
||
call(#foo, _movie, 1, 2, 3)</ |
call(#foo, _movie, 1, 2, 3)</syntaxhighlight> |
||
*Calling a function with optional arguments |
*Calling a function with optional arguments |
||
< |
<syntaxhighlight lang=lingo>on foo (a, b) |
||
if voidP(b) then b = 1 |
if voidP(b) then b = 1 |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang=lingo>put foo(23, 2) |
||
-- 46 |
-- 46 |
||
put foo(23) |
put foo(23) |
||
-- 23</ |
-- 23</syntaxhighlight> |
||
*Calling a function with a variable number of arguments |
*Calling a function with a variable number of arguments |
||
< |
<syntaxhighlight lang=lingo>on sum () |
||
res = 0 |
res = 0 |
||
repeat with i = 1 to the paramCount |
repeat with i = 1 to the paramCount |
||
Line 3,343: | Line 3,343: | ||
end repeat |
end repeat |
||
return res |
return res |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang=lingo>put sum (1,2,3) |
||
-- 6</ |
-- 6</syntaxhighlight> |
||
*Calling a function with named arguments |
*Calling a function with named arguments |
||
Line 3,353: | Line 3,353: | ||
*Using a function in first-class context within an expression |
*Using a function in first-class context within an expression |
||
Lingo has no first-class functions, but the call(...) syntax (see above) allows to identify and use functions specified as "symbols" (e.g. #foo). This allows some "first-class alike" features: |
Lingo has no first-class functions, but the call(...) syntax (see above) allows to identify and use functions specified as "symbols" (e.g. #foo). This allows some "first-class alike" features: |
||
< |
<syntaxhighlight lang=lingo>---------------------------------------- |
||
-- One of the five native iterative methods defined in ECMAScript 5 |
-- One of the five native iterative methods defined in ECMAScript 5 |
||
-- @param {list} tList |
-- @param {list} tList |
||
Line 3,372: | Line 3,372: | ||
on doubleInt (n) |
on doubleInt (n) |
||
return n*2 |
return n*2 |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang=lingo>l = [1,2,3] |
||
put map(l, #doubleInt) |
put map(l, #doubleInt) |
||
-- [2, 4, 6]</ |
-- [2, 4, 6]</syntaxhighlight> |
||
*Obtaining the return value of a function |
*Obtaining the return value of a function |
||
< |
<syntaxhighlight lang=lingo>x = foo(1,2)</syntaxhighlight> |
||
*Distinguishing built-in functions and user-defined functions |
*Distinguishing built-in functions and user-defined functions |
||
In Lingo all user-defined (global) functions are 'methods' of the _movie object, and there is AFAIK no direct way to distinguish those from _movie's built-in functions. But by iterating over of all movie scripts in all castlibs you can get a complete list of all user-defined (global) functions, and then any function not in this list is a built-in function: |
In Lingo all user-defined (global) functions are 'methods' of the _movie object, and there is AFAIK no direct way to distinguish those from _movie's built-in functions. But by iterating over of all movie scripts in all castlibs you can get a complete list of all user-defined (global) functions, and then any function not in this list is a built-in function: |
||
< |
<syntaxhighlight lang=lingo>on getAllUserFunctions () |
||
res = [] |
res = [] |
||
repeat with i = 1 to _movie.castlib.count |
repeat with i = 1 to _movie.castlib.count |
||
Line 3,398: | Line 3,398: | ||
end repeat |
end repeat |
||
return res |
return res |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang=lingo>put getAllUserFunctions() |
||
-- [#sum, #double, #getAllUserFunctions]</ |
-- [#sum, #double, #getAllUserFunctions]</syntaxhighlight> |
||
*Distinguishing subroutines and functions |
*Distinguishing subroutines and functions |
||
Line 3,407: | Line 3,407: | ||
*Stating whether arguments are passed by value or by reference |
*Stating whether arguments are passed by value or by reference |
||
In lingo 'objects' are always passed by reference, all other types (e.g. strings, integers, floats) by value. 'Objects' are e.g. lists (arrays), property lists (hashes), images and script instances. The built-in function objectP() returns TRUE (1) for objects and FALSE (0) for non-objects. To prevent the effects of call-by-reference, some object types (lists, property lists and images) support the method duplicate() to clone the object before passing it to a function: |
In lingo 'objects' are always passed by reference, all other types (e.g. strings, integers, floats) by value. 'Objects' are e.g. lists (arrays), property lists (hashes), images and script instances. The built-in function objectP() returns TRUE (1) for objects and FALSE (0) for non-objects. To prevent the effects of call-by-reference, some object types (lists, property lists and images) support the method duplicate() to clone the object before passing it to a function: |
||
< |
<syntaxhighlight lang=lingo>on double (someList) |
||
cnt = someList.count |
cnt = someList.count |
||
repeat with i = 1 to cnt |
repeat with i = 1 to cnt |
||
someList[i] = someList[i] * 2 |
someList[i] = someList[i] * 2 |
||
end repeat |
end repeat |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang=lingo>l = [1,2,3] |
||
double(l) |
double(l) |
||
put l |
put l |
||
Line 3,421: | Line 3,421: | ||
double(l.duplicate()) |
double(l.duplicate()) |
||
put l |
put l |
||
-- [1, 2, 3]</ |
-- [1, 2, 3]</syntaxhighlight> |
||
=={{header|Little}}== |
=={{header|Little}}== |
||
Line 3,428: | Line 3,428: | ||
local fuctions. |
local fuctions. |
||
< |
<syntaxhighlight lang=C>// Calling a function that requires no arguments |
||
void foo() {puts("Calling a function with no arguments");} |
void foo() {puts("Calling a function with no arguments");} |
||
foo(); |
foo(); |
||
Line 3,462: | Line 3,462: | ||
puts (a); |
puts (a); |
||
puts (b); |
puts (b); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang=lua>-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped. |
||
function fixed (a, b, c) print(a, b, c) end |
function fixed (a, b, c) print(a, b, c) end |
||
fixed() --> nil nil nil |
fixed() --> nil nil nil |
||
Line 3,497: | Line 3,497: | ||
-- There is no separate notion of subroutines |
-- There is no separate notion of subroutines |
||
-- Built-in functions are not easily distinguishable from user-defined functions |
-- Built-in functions are not easily distinguishable from user-defined functions |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Luck}}== |
=={{header|Luck}}== |
||
< |
<syntaxhighlight lang=luck>/* Calling a function that requires no arguments */ |
||
f();; |
f();; |
||
Line 3,542: | Line 3,542: | ||
/* Is partial application possible and how */ |
/* Is partial application possible and how */ |
||
tasty_curry(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z);;</ |
tasty_curry(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z);;</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
Line 3,631: | Line 3,631: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
Calling a function with no arguments:<lang |
Calling a function with no arguments:<syntaxhighlight lang=Maple> f()</syntaxhighlight> |
||
Calling a function with a fixed number of arguments:< |
Calling a function with a fixed number of arguments:<syntaxhighlight lang=Maple>f(1,sin(x), g -> int(g(t),t=0..1)</syntaxhighlight> |
||
Calling a function with optional arguments: < |
Calling a function with optional arguments: <syntaxhighlight lang=Maple>f(1, sin(x), g -> int(g(t),t=0..1)</syntaxhighlight> |
||
Calling a function with a variable number of arguments: < |
Calling a function with a variable number of arguments: <syntaxhighlight lang=Maple>f(1, sin(x), g -> int(g(t),t=0..1)</syntaxhighlight> |
||
Calling a function with named arguments:< |
Calling a function with named arguments:<syntaxhighlight lang=Maple>f(a,b,method = foo)</syntaxhighlight> |
||
Calling a function in a statements context:< |
Calling a function in a statements context:<syntaxhighlight lang=Maple>f(a); f(b);</syntaxhighlight> |
||
Using a function in first-class context within an expression:< |
Using a function in first-class context within an expression:<syntaxhighlight lang=Maple>f(a) + g(b)</syntaxhighlight> |
||
Obtaining the return value of a function:< |
Obtaining the return value of a function:<syntaxhighlight lang=Maple> x := f(1)</syntaxhighlight> |
||
Distinguishing built-in functions and user-defined functions: |
Distinguishing built-in functions and user-defined functions: |
||
< |
<syntaxhighlight lang=Maple>> type( op, 'builtin' ); |
||
true |
true |
||
</syntaxhighlight> |
|||
</lang> |
|||
Distinguishing subroutines and functions: There is no distinction. |
Distinguishing subroutines and functions: There is no distinction. |
||
Line 3,652: | Line 3,652: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Calling a function that requires no arguments: |
Calling a function that requires no arguments: |
||
<lang |
<syntaxhighlight lang=Mathematica>f[]</syntaxhighlight> |
||
Calling a function with a fixed number of arguments: |
Calling a function with a fixed number of arguments: |
||
<lang |
<syntaxhighlight lang=Mathematica>f[1,2]</syntaxhighlight> |
||
Calling a function with optional arguments: |
Calling a function with optional arguments: |
||
<lang |
<syntaxhighlight lang=Mathematica>f[1,Option1->True]</syntaxhighlight> |
||
Calling a function with a variable number of arguments: |
Calling a function with a variable number of arguments: |
||
< |
<syntaxhighlight lang=Mathematica>f[1,Option1->True] |
||
f[1,Option1->True,Option2->False]</ |
f[1,Option1->True,Option2->False]</syntaxhighlight> |
||
Calling a function with named arguments: |
Calling a function with named arguments: |
||
< |
<syntaxhighlight lang=Mathematica>f[Option1->True,Option2->False]</syntaxhighlight> |
||
Using a function in statement context: |
Using a function in statement context: |
||
< |
<syntaxhighlight lang=Mathematica>f[1,2];f[2,3]</syntaxhighlight> |
||
Using a function in first-class context within an expression: |
Using a function in first-class context within an expression: |
||
<lang |
<syntaxhighlight lang=Mathematica>(#^2)&[3];</syntaxhighlight> |
||
The return value of a function can be formally extracted using Return[] |
The return value of a function can be formally extracted using Return[] |
||
Line 3,679: | Line 3,679: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang=Matlab> |
||
% Calling a function that requires no arguments |
% Calling a function that requires no arguments |
||
function a=foo(); |
function a=foo(); |
||
Line 3,729: | Line 3,729: | ||
% Stating whether arguments are passed by value or by reference |
% Stating whether arguments are passed by value or by reference |
||
% arguments are passed by value, however Matlab has delayed evaluation, such that a copy of large data structures are done only when an element is written to. |
% arguments are passed by value, however Matlab has delayed evaluation, such that a copy of large data structures are done only when an element is written to. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang=nanoquery>// function with no arguments |
||
no_args() |
no_args() |
||
Line 3,749: | Line 3,749: | ||
catch |
catch |
||
println "func is a built-in or doesn't exist" |
println "func is a built-in or doesn't exist" |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang=Nemerle>// no arguments |
||
f() |
f() |
||
Line 3,808: | Line 3,808: | ||
def h = f(_, 2) |
def h = f(_, 2) |
||
def a = g(3) // equivalent to: def a = f(2, 3) |
def a = g(3) // equivalent to: def a = f(2, 3) |
||
def b = h(3) // equivalent to: def b = f(3, 2)</ |
def b = h(3) // equivalent to: def b = f(3, 2)</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Translated from Python, when possible: |
Translated from Python, when possible: |
||
< |
<syntaxhighlight lang=nim>proc no_args() = |
||
discard |
discard |
||
# call |
# call |
||
Line 3,854: | Line 3,854: | ||
let x = return_something(19) + 10 |
let x = return_something(19) + 10 |
||
let y = 19.return_something() + 10 |
let y = 19.return_something() + 10 |
||
let z = 19.return_something + 10</ |
let z = 19.return_something + 10</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 3,860: | Line 3,860: | ||
* Calling a function that requires no arguments: |
* Calling a function that requires no arguments: |
||
<lang |
<syntaxhighlight lang=ocaml>f ()</syntaxhighlight> |
||
(In fact it is impossible to call a function without arguments, when there are no particular arguments we provide the type <code>unit</code> which is a type that has only one possible value. This type is mainly made for this use.) |
(In fact it is impossible to call a function without arguments, when there are no particular arguments we provide the type <code>unit</code> which is a type that has only one possible value. This type is mainly made for this use.) |
||
Line 3,866: | Line 3,866: | ||
* Calling a function with a fixed number of arguments: |
* Calling a function with a fixed number of arguments: |
||
<lang |
<syntaxhighlight lang=ocaml>f 1 2 3</syntaxhighlight> |
||
* Calling a function with optional arguments: |
* Calling a function with optional arguments: |
||
Line 3,872: | Line 3,872: | ||
For a function that has this signature: |
For a function that has this signature: |
||
< |
<syntaxhighlight lang=ocaml>val f : ?a:int -> int -> unit</syntaxhighlight> |
||
here is how to call it with or without the first argument omited: |
here is how to call it with or without the first argument omited: |
||
< |
<syntaxhighlight lang=ocaml>f 10 |
||
f ~a:6 10</ |
f ~a:6 10</syntaxhighlight> |
||
Due to partial application, an optional argument always has to be followed by a non-optional argument. If the function needs no additional arguments then we use the type <code>unit</code>: |
Due to partial application, an optional argument always has to be followed by a non-optional argument. If the function needs no additional arguments then we use the type <code>unit</code>: |
||
< |
<syntaxhighlight lang=ocaml>g () |
||
g ~b:1.0 ()</ |
g ~b:1.0 ()</syntaxhighlight> |
||
* Calling a function with a variable number of arguments: |
* Calling a function with a variable number of arguments: |
||
Line 3,894: | Line 3,894: | ||
Named arguments are called '''labels'''. |
Named arguments are called '''labels'''. |
||
<lang |
<syntaxhighlight lang=ocaml>f ~arg:3</syntaxhighlight> |
||
If a variable has the same name than the label we can use this simpler syntax: |
If a variable has the same name than the label we can use this simpler syntax: |
||
< |
<syntaxhighlight lang=ocaml>let arg = 3 in |
||
f ~arg</ |
f ~arg</syntaxhighlight> |
||
* Using a function in statement context: |
* Using a function in statement context: |
||
<lang |
<syntaxhighlight lang=ocaml>(* TODO *)</syntaxhighlight> |
||
* Using a function in first-class context within an expression: |
* Using a function in first-class context within an expression: |
||
Line 3,911: | Line 3,911: | ||
* Obtaining the return value of a function: |
* Obtaining the return value of a function: |
||
< |
<syntaxhighlight lang=ocaml>let ret = f () |
||
let a, b, c = f () (* if there are several returned values given as a tuple *) |
let a, b, c = f () (* if there are several returned values given as a tuple *) |
||
let _ = f () (* if we want to ignore the returned value *) |
let _ = f () (* if we want to ignore the returned value *) |
||
let v, _ = f () (* if we want to ignore one of the returned value *)</ |
let v, _ = f () (* if we want to ignore one of the returned value *)</syntaxhighlight> |
||
* Distinguishing built-in functions and user-defined functions: |
* Distinguishing built-in functions and user-defined functions: |
||
Line 3,941: | Line 3,941: | ||
If f is a function and c b a ares objects : |
If f is a function and c b a ares objects : |
||
<lang |
<syntaxhighlight lang=Oforth>a b c f</syntaxhighlight> |
||
will push c then b then a on the stack then call f. Calling f does not describe if f will use 1, 2 or 3 arguments (or none). |
will push c then b then a on the stack then call f. Calling f does not describe if f will use 1, 2 or 3 arguments (or none). |
||
Oforth adds a notation to describe parameters used by a function. It is only a way to add information about which parameters will be used by f : |
Oforth adds a notation to describe parameters used by a function. It is only a way to add information about which parameters will be used by f : |
||
<lang |
<syntaxhighlight lang=Oforth>f(a, b, c)</syntaxhighlight> |
||
Intepreter will replace this second syntax by the first one. It is only "sugar"... |
Intepreter will replace this second syntax by the first one. It is only "sugar"... |
||
< |
<syntaxhighlight lang=Oforth>a b c f |
||
a b f(c) |
a b f(c) |
||
a f(b, c) |
a f(b, c) |
||
f(a, b, c)</ |
f(a, b, c)</syntaxhighlight> |
||
are the same call to function f and the interpreter will translate all of them into the first one. Which parameters are really used by f will depend on f implementation. |
are the same call to function f and the interpreter will translate all of them into the first one. Which parameters are really used by f will depend on f implementation. |
||
Line 3,958: | Line 3,958: | ||
Methods need a receiver (the object on which the method will apply and the object that will pushed on th stack when self is used into the method body). |
Methods need a receiver (the object on which the method will apply and the object that will pushed on th stack when self is used into the method body). |
||
The receiver must be on the top of the stack before calling the method. If a, b, c and r are objects and m a method : |
The receiver must be on the top of the stack before calling the method. If a, b, c and r are objects and m a method : |
||
<lang |
<syntaxhighlight lang=Oforth>a b c r m</syntaxhighlight> |
||
will call m with r as its receiver. |
will call m with r as its receiver. |
||
It is also possible to use the same "sugar" notation used by functions : |
It is also possible to use the same "sugar" notation used by functions : |
||
< |
<syntaxhighlight lang=Oforth>r m(a, b, c)</syntaxhighlight> |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang=scheme> |
||
; note: sign "==>" indicates expected output |
; note: sign "==>" indicates expected output |
||
Line 4,103: | Line 4,103: | ||
;;; Stating whether arguments are passed by value or by reference |
;;; Stating whether arguments are passed by value or by reference |
||
; The values in Ol always passed as values and objects always passed as references. If you want to pass an object copy - make a copy by yourself. |
; The values in Ol always passed as values and objects always passed as references. If you want to pass an object copy - make a copy by yourself. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
This is to show how a built-in function is invoked when an internal function on the dame name in present. |
This is to show how a built-in function is invoked when an internal function on the dame name in present. |
||
< |
<syntaxhighlight lang=oorexx>say 'DATE'() |
||
Say date() |
Say date() |
||
Exit |
Exit |
||
daTe: Return 'my date' </ |
daTe: Return 'my date' </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>H:\>rexx fdate |
<pre>H:\>rexx fdate |
||
Line 4,122: | Line 4,122: | ||
Functions can be used when statements would be expected without change. |
Functions can be used when statements would be expected without change. |
||
< |
<syntaxhighlight lang=parigp>f(); \\ zero arguments |
||
sin(Pi/2); \\ fixed number of arguments |
sin(Pi/2); \\ fixed number of arguments |
||
vecsort([5,6]) != vecsort([5,6],,4) \\ optional arguments |
vecsort([5,6]) != vecsort([5,6],,4) \\ optional arguments |
||
Line 4,128: | Line 4,128: | ||
call(Str, ["gg", 1, "hh"]) \\ variable number of arguments in a vector |
call(Str, ["gg", 1, "hh"]) \\ variable number of arguments in a vector |
||
(x->x^2)(3); \\ first-class |
(x->x^2)(3); \\ first-class |
||
x = sin(0); \\ get function value</ |
x = sin(0); \\ get function value</syntaxhighlight> |
||
Built-in functions are like user-defined functions in current versions. In older versions built-in functions cannot be passed as closures. |
Built-in functions are like user-defined functions in current versions. In older versions built-in functions cannot be passed as closures. |
||
Line 4,138: | Line 4,138: | ||
Calling a nullary function and obtaining its return value: |
Calling a nullary function and obtaining its return value: |
||
<lang |
<syntaxhighlight lang=pascal>foo</syntaxhighlight> |
||
Calling an n-ary function (n ≥ 1) and obtaining its return value: |
Calling an n-ary function (n ≥ 1) and obtaining its return value: |
||
< |
<syntaxhighlight lang=pascal>foo(1, 'abc', true)</syntaxhighlight> |
||
Following are not possible in Pascal as defined by the ISO standards (ISO 7185 and ISO 10206). |
Following are not possible in Pascal as defined by the ISO standards (ISO 7185 and ISO 10206). |
||
Line 4,154: | Line 4,154: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
The most common syntax; simply calls the function foo on the argument(s) provided. |
The most common syntax; simply calls the function foo on the argument(s) provided. |
||
< |
<syntaxhighlight lang=perl>foo(); # Call foo on the null list |
||
&foo(); # Ditto |
&foo(); # Ditto |
||
foo($arg1, $arg2); # Call foo on $arg1 and $arg2 |
foo($arg1, $arg2); # Call foo on $arg1 and $arg2 |
||
&foo($arg1, $arg2); # Ditto; ignores prototypes</ |
&foo($arg1, $arg2); # Ditto; ignores prototypes</syntaxhighlight> |
||
Call foo() as a bareword. Only works after the function has been declared, which |
Call foo() as a bareword. Only works after the function has been declared, which |
||
can be done normally or with the use subs pragma. |
can be done normally or with the use subs pragma. |
||
<lang |
<syntaxhighlight lang=perl>foo;</syntaxhighlight> |
||
Call foo() with the current values of @_<lang |
Call foo() with the current values of @_<syntaxhighlight lang=perl>&foo;</syntaxhighlight> |
||
Call foo() with the current values of @_, discarding the previous stack frame. Not your grandfather's (harmful) goto, although the keyword can do both.<lang |
Call foo() with the current values of @_, discarding the previous stack frame. Not your grandfather's (harmful) goto, although the keyword can do both.<syntaxhighlight lang=perl>goto &foo;</syntaxhighlight> |
||
For subroutines stored in references (anonymous subroutines).< |
For subroutines stored in references (anonymous subroutines).<syntaxhighlight lang=perl>&$fooref('foo', 'bar'); |
||
&{$fooref}('foo', 'bar'); |
&{$fooref}('foo', 'bar'); |
||
$fooref->('foo', 'bar');</ |
$fooref->('foo', 'bar');</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Line 4,173: | Line 4,173: | ||
* Phix does not allow implicit discard of function results. The explicit discard statement takes the form |
* Phix does not allow implicit discard of function results. The explicit discard statement takes the form |
||
<!--< |
<!--<syntaxhighlight lang=Phix>--> |
||
<span style="color: #0000FF;">{<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #0000FF;">) |
<span style="color: #0000FF;">{<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #0000FF;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
* This is in fact a simple contraction of standard multiple assigment (which can be nested as deeply as you like): |
* This is in fact a simple contraction of standard multiple assigment (which can be nested as deeply as you like): |
||
<!--< |
<!--<syntaxhighlight lang=Phix>--> |
||
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">,<span style="color: #000000;">populations<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">,<span style="color: #000000;">populations<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> |
||
<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #000000;">populations<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- discard result[1]</span> |
<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #000000;">populations<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- discard result[1]</span> |
||
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">}<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- discard result[2]</span> |
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">}<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- discard result[2]</span> |
||
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "" |
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "" |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
* Calling a function with no parameters still requires the "()" empty argument list. |
* Calling a function with no parameters still requires the "()" empty argument list. |
||
* Optional arguments are denoted simply by the presence of a default, and must be grouped on the right: |
* Optional arguments are denoted simply by the presence of a default, and must be grouped on the right: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">b<span style="color: #0000FF;">=<span style="color: #008000;">"default"<span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">b<span style="color: #0000FF;">=<span style="color: #008000;">"default"<span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{<span style="color: #000000;">a<span style="color: #0000FF;">,<span style="color: #000000;">b<span style="color: #0000FF;">}</span> |
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{<span style="color: #000000;">a<span style="color: #0000FF;">,<span style="color: #000000;">b<span style="color: #0000FF;">}</span> |
||
Line 4,195: | Line 4,195: | ||
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {1,"default"}</span> |
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {1,"default"}</span> |
||
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">2<span style="color: #0000FF;">,<span style="color: #008000;">"that"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {2,"that"} |
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">2<span style="color: #0000FF;">,<span style="color: #008000;">"that"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {2,"that"} |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
* Sequence parameters can be of any length, which is another way to implement optional/variable number of arguments. |
* Sequence parameters can be of any length, which is another way to implement optional/variable number of arguments. |
||
* Named arguments can be specified in any order, with an error if any non-optional parameters are missing: |
* Named arguments can be specified in any order, with an error if any non-optional parameters are missing: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>--> |
||
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">b<span style="color: #0000FF;">:=<span style="color: #008000;">"then"<span style="color: #0000FF;">,<span style="color: #000000;">a<span style="color: #0000FF;">:=<span style="color: #000000;">3<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {3,"then"} |
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">b<span style="color: #0000FF;">:=<span style="color: #008000;">"then"<span style="color: #0000FF;">,<span style="color: #000000;">a<span style="color: #0000FF;">:=<span style="color: #000000;">3<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {3,"then"} |
||
--?myfunction(b:="though") -- compile-time error |
--?myfunction(b:="though") -- compile-time error |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
* The programmer is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first). |
* The programmer is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first). |
||
* Phix support first-class functions directly, as integers, along with an older routine_id mechanism: |
* Phix support first-class functions directly, as integers, along with an older routine_id mechanism: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>--> |
||
<span style="color: #008080;">constant</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">r_myfunction</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">routine_id<span style="color: #0000FF;">(<span style="color: #008000;">"myfunction"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
<span style="color: #008080;">constant</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">r_myfunction</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">routine_id<span style="color: #0000FF;">(<span style="color: #008000;">"myfunction"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
||
<span style="color: #000000;">first_class</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">myfunction</span> |
<span style="color: #000000;">first_class</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">myfunction</span> |
||
Line 4,215: | Line 4,215: | ||
<span style="color: #0000FF;">?<span style="color: #7060A8;">call_func<span style="color: #0000FF;">(<span style="color: #000000;">first_class<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">1<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ""</span> |
<span style="color: #0000FF;">?<span style="color: #7060A8;">call_func<span style="color: #0000FF;">(<span style="color: #000000;">first_class<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">1<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- ""</span> |
||
<span style="color: #0000FF;">?<span style="color: #000000;">first_class<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "" |
<span style="color: #0000FF;">?<span style="color: #000000;">first_class<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- "" |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
The value of r_my_func can be passed as an argument to any routine, or stored in a table, and invoked in a similar fashion.<br> |
The value of r_my_func can be passed as an argument to any routine, or stored in a table, and invoked in a similar fashion.<br> |
||
Line 4,225: | Line 4,225: | ||
* All arguments are passed by reference with copy-on-write semantics: to modify the value of a parameter you must both return and assign it, as in: |
* All arguments are passed by reference with copy-on-write semantics: to modify the value of a parameter you must both return and assign it, as in: |
||
<!--< |
<!--<syntaxhighlight lang=Phix>--> |
||
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">item<span style="color: #0000FF;">) |
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">item<span style="color: #0000FF;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
* Implicit forward calls are supported, as are optional explicit forward declarations, which can occasionally cure compilation error messages. |
* Implicit forward calls are supported, as are optional explicit forward declarations, which can occasionally cure compilation error messages. |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang=Phixmonti>def saludo |
||
"Hola mundo" print nl |
"Hola mundo" print nl |
||
enddef |
enddef |
||
Line 4,238: | Line 4,238: | ||
saludo |
saludo |
||
getid saludo exec</ |
getid saludo exec</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
When calling a funcion in PicoLisp directly (does this mean "in a statement context"?), it is always surrounded by parentheses, with or without arguments, and for any kind of arguments (evaluated or not): |
When calling a funcion in PicoLisp directly (does this mean "in a statement context"?), it is always surrounded by parentheses, with or without arguments, and for any kind of arguments (evaluated or not): |
||
< |
<syntaxhighlight lang=PicoLisp>(foo) |
||
(bar 1 'arg 2 'mumble)</ |
(bar 1 'arg 2 'mumble)</syntaxhighlight> |
||
When a function is used in a "first class context" (e.g. passed to another function), then it is not yet '''called'''. It is simply '''used'''. Technically, a function can be either a '''number''' (a built-in function) or a '''list''' (a Lisp-level function) in PicoLisp): |
When a function is used in a "first class context" (e.g. passed to another function), then it is not yet '''called'''. It is simply '''used'''. Technically, a function can be either a '''number''' (a built-in function) or a '''list''' (a Lisp-level function) in PicoLisp): |
||
< |
<syntaxhighlight lang=PicoLisp>(mapc println Lst) # The value of 'printlin' is a number |
||
(apply '((A B C) (foo (+ A (* B C)))) (3 5 7)) # A list is passed</ |
(apply '((A B C) (foo (+ A (* B C)))) (3 5 7)) # A list is passed</syntaxhighlight> |
||
Any argument to a function may be evaluated or not, depending on the function. For example, 'setq' evaluates every second argument |
Any argument to a function may be evaluated or not, depending on the function. For example, 'setq' evaluates every second argument |
||
< |
<syntaxhighlight lang=PicoLisp>(setq A (+ 3 4) B (* 3 4))</syntaxhighlight> |
||
i.e. the first argument 'A' is not evaluated, the second evaluates to 7, 'B' is not evaluated, then the fourth evaluates to 12. |
i.e. the first argument 'A' is not evaluated, the second evaluates to 7, 'B' is not evaluated, then the fourth evaluates to 12. |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang=PureBasic>Procedure Saludo() |
||
PrintN("Hola mundo!") |
PrintN("Hola mundo!") |
||
EndProcedure |
EndProcedure |
||
Line 4,290: | Line 4,290: | ||
Input() |
Input() |
||
CloseConsole()</ |
CloseConsole()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as FreeBASIC entry.</pre> |
<pre>Same as FreeBASIC entry.</pre> |
||
Line 4,297: | Line 4,297: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
Under the hood all Python function/method parameters are named. All arguments can be passed as ''name=value'' pairs or as a dictionary containing such pairs using the ''myfunc('''**key_args''')'' (apply over dictionary) syntax). One can also "apply" a function over a sequence of arguments using the syntax: ''myfunc('''*args''')'' as noted in comments below. Parameters can be mixed so long parameters with default values (optional arguments) follow any "positional" (required) parameters, and catchall parameter ('''''*args''''') follow those, and any "keyword arguments' parameter" is last. (Any function can only have up to one "catchall" or '''''*args'''' parameter and up to one "keyword args" '''''**kwargs''''' parameter). |
Under the hood all Python function/method parameters are named. All arguments can be passed as ''name=value'' pairs or as a dictionary containing such pairs using the ''myfunc('''**key_args''')'' (apply over dictionary) syntax). One can also "apply" a function over a sequence of arguments using the syntax: ''myfunc('''*args''')'' as noted in comments below. Parameters can be mixed so long parameters with default values (optional arguments) follow any "positional" (required) parameters, and catchall parameter ('''''*args''''') follow those, and any "keyword arguments' parameter" is last. (Any function can only have up to one "catchall" or '''''*args'''' parameter and up to one "keyword args" '''''**kwargs''''' parameter). |
||
< |
<syntaxhighlight lang=python>def no_args(): |
||
pass |
pass |
||
# call |
# call |
||
Line 4,366: | Line 4,366: | ||
## For partial function application see: |
## For partial function application see: |
||
## http://rosettacode.org/wiki/Partial_function_application#Python</ |
## http://rosettacode.org/wiki/Partial_function_application#Python</syntaxhighlight> |
||
Line 4,373: | Line 4,373: | ||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang=qbasic>FUNCTION Copialo$ (txt$, siNo, final$) |
||
DIM nuevaCadena$ |
DIM nuevaCadena$ |
||
Line 4,404: | Line 4,404: | ||
CALL testNumeros(1, 2, 0) |
CALL testNumeros(1, 2, 0) |
||
PRINT |
PRINT |
||
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")</ |
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,449: | Line 4,449: | ||
=={{header|R}}== |
=={{header|R}}== |
||
Translated from Python, when possible. |
Translated from Python, when possible. |
||
< |
<syntaxhighlight lang=rsplus>### Calling a function that requires no arguments |
||
no_args <- function() NULL |
no_args <- function() NULL |
||
no_args() |
no_args() |
||
Line 4,506: | Line 4,506: | ||
### Is partial application possible and how |
### Is partial application possible and how |
||
# Yes, see http://rosettacode.org/wiki/Partial_function_application#R</ |
# Yes, see http://rosettacode.org/wiki/Partial_function_application#R</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang=Racket> |
||
#lang racket |
#lang racket |
||
Line 4,549: | Line 4,549: | ||
(curry foo 1 2) ; later apply this on 3 |
(curry foo 1 2) ; later apply this on 3 |
||
(λ(x) (foo 1 2 x)) ; a direct way of doing the same |
(λ(x) (foo 1 2 x)) ; a direct way of doing the same |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 4,563: | Line 4,563: | ||
Calling a function that requires no arguments: |
Calling a function that requires no arguments: |
||
<lang |
<syntaxhighlight lang=raku line>foo # as list operator |
||
foo() # as function |
foo() # as function |
||
foo.() # as function, explicit postfix form |
foo.() # as function, explicit postfix form |
||
Line 4,570: | Line 4,570: | ||
&foo() # as object invocation |
&foo() # as object invocation |
||
&foo.() # as object invocation, explicit postfix |
&foo.() # as object invocation, explicit postfix |
||
::($name)() # as symbolic ref</ |
::($name)() # as symbolic ref</syntaxhighlight> |
||
Calling a function with exactly one argument: |
Calling a function with exactly one argument: |
||
<lang |
<syntaxhighlight lang=raku line>foo 1 # as list operator |
||
foo(1) # as named function |
foo(1) # as named function |
||
foo.(1) # as named function, explicit postfix |
foo.(1) # as named function, explicit postfix |
||
Line 4,586: | Line 4,586: | ||
1.foo() # as method via dispatcher |
1.foo() # as method via dispatcher |
||
1."$name"() # as method via dispatcher, symbolic |
1."$name"() # as method via dispatcher, symbolic |
||
+1 # as operator to prefix:<+> function</ |
+1 # as operator to prefix:<+> function</syntaxhighlight> |
||
Method calls are included here because they do eventually dispatch to a true |
Method calls are included here because they do eventually dispatch to a true |
||
Line 4,608: | Line 4,608: | ||
Calling a function with exactly two arguments: |
Calling a function with exactly two arguments: |
||
<lang |
<syntaxhighlight lang=raku line>foo 1,2 # as list operator |
||
foo(1,2) # as named function |
foo(1,2) # as named function |
||
foo.(1,2) # as named function, explicit postfix |
foo.(1,2) # as named function, explicit postfix |
||
Line 4,620: | Line 4,620: | ||
1.foo(2) # as method via dispatcher |
1.foo(2) # as method via dispatcher |
||
1."$name"(2) # as method via dispatcher, symbolic |
1."$name"(2) # as method via dispatcher, symbolic |
||
1 + 2 # as operator to infix:<+> function</ |
1 + 2 # as operator to infix:<+> function</syntaxhighlight> |
||
Optional arguments don't look any different from normal arguments. |
Optional arguments don't look any different from normal arguments. |
||
Line 4,627: | Line 4,627: | ||
Calling a function with a variable number of arguments (varargs): |
Calling a function with a variable number of arguments (varargs): |
||
<lang |
<syntaxhighlight lang=raku line>foo @args # as list operator |
||
foo(@args) # as named function |
foo(@args) # as named function |
||
foo.(@args) # as named function, explicit postfix |
foo.(@args) # as named function, explicit postfix |
||
Line 4,639: | Line 4,639: | ||
1.foo(@args) # as method via dispatcher |
1.foo(@args) # as method via dispatcher |
||
1."$name"(@args) # as method via dispatcher, symbolic |
1."$name"(@args) # as method via dispatcher, symbolic |
||
@args X @blargs # as list infix operator to infix:<X></ |
@args X @blargs # as list infix operator to infix:<X></syntaxhighlight> |
||
Note: whether a function may actually be called with a variable number of arguments depends entirely |
Note: whether a function may actually be called with a variable number of arguments depends entirely |
||
on whether a signature accepts a list at that position in the argument list, but |
on whether a signature accepts a list at that position in the argument list, but |
||
Line 4,645: | Line 4,645: | ||
foo function is declared with a signature of the form (*@params). The calls above might be interpreted as having a single array argument if the signature indicates a normal parameter instead of a variadic one. What you cannot do in Raku (unlike Perl 5) is pass an array as several fixed arguments. By default it must either represent a single argument, or be part of a variadic list. You can force the extra level of argument list interpolation using a prefix <tt>|</tt> however: |
foo function is declared with a signature of the form (*@params). The calls above might be interpreted as having a single array argument if the signature indicates a normal parameter instead of a variadic one. What you cannot do in Raku (unlike Perl 5) is pass an array as several fixed arguments. By default it must either represent a single argument, or be part of a variadic list. You can force the extra level of argument list interpolation using a prefix <tt>|</tt> however: |
||
<lang |
<syntaxhighlight lang=raku line>my @args = 1,2,3; |
||
foo(|@args); # equivalent to foo(1,2,3)</ |
foo(|@args); # equivalent to foo(1,2,3)</syntaxhighlight> |
||
Calling a function with named arguments: |
Calling a function with named arguments: |
||
<lang |
<syntaxhighlight lang=raku line>foo :a, :b(4), :!c, d => "stuff" |
||
foo(:a, :b(4), :!c, d => "stuff")</ |
foo(:a, :b(4), :!c, d => "stuff")</syntaxhighlight> |
||
...and so on. Operators may also be called with named arguments, but only |
...and so on. Operators may also be called with named arguments, but only |
||
colon adverbials are allowed: |
colon adverbials are allowed: |
||
<lang |
<syntaxhighlight lang=raku line>1 + 1 :a :b(4) :!c :d("stuff") # calls infix:<+>(1,1,:a, :b(4), :!c, d => "stuff")</syntaxhighlight> |
||
Using a function in statement context: |
Using a function in statement context: |
||
<lang |
<syntaxhighlight lang=raku line>foo(); bar(); baz(); # evaluate for side effects</syntaxhighlight> |
||
Using a function in first class context within an expression: |
Using a function in first class context within an expression: |
||
<lang |
<syntaxhighlight lang=raku line>1 / find-a-func(1,2,3)(4,5,6) ** 2;</syntaxhighlight> |
||
Obtaining the return value of a function: |
Obtaining the return value of a function: |
||
<lang |
<syntaxhighlight lang=raku line>my $result = somefunc(1,2,3) + 2;</syntaxhighlight> |
||
There is no difference between calling builtins and user-defined functions and operators (or |
There is no difference between calling builtins and user-defined functions and operators (or |
||
Line 4,681: | Line 4,681: | ||
===Practice=== |
===Practice=== |
||
Demonstrating each of the above-mentioned function calls with actual running code, along with the various extra definitions required to make them work (in certain cases). Arguments are checked, and function name / run-sequence number are displayed upon success. |
Demonstrating each of the above-mentioned function calls with actual running code, along with the various extra definitions required to make them work (in certain cases). Arguments are checked, and function name / run-sequence number are displayed upon success. |
||
<lang |
<syntaxhighlight lang=raku line>{ |
||
state $n; |
state $n; |
||
Line 4,771: | Line 4,771: | ||
f(|@args); # 45 equivalent to f(1,2,3) |
f(|@args); # 45 equivalent to f(1,2,3) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>f1 f2 i3 f4 f5 f6 f7 f8 f9 f10 l11 f12 f13 f14 f15 f16 f17 j18 j19 j20 f21 f22 m23 f24 f25 f26 f27 f28 f29 k30 k31 k32 f33 f34 n35 f36 f37 g38 g39 g40 g41 h42 h43 h44 f45</pre> |
<pre>f1 f2 i3 f4 f5 f6 f7 f8 f9 f10 l11 f12 f13 f14 f15 f16 f17 j18 j19 j20 f21 f22 m23 f24 f25 f26 f27 f28 f29 k30 k31 k32 f33 f34 n35 f36 f37 g38 g39 g40 g41 h42 h43 h44 f45</pre> |
||
Line 4,777: | Line 4,777: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang=rexx>/*REXX pgms demonstrates various methods/approaches of invoking/calling a REXX function.*/ |
||
/*╔════════════════════════════════════════════════════════════════════╗ |
/*╔════════════════════════════════════════════════════════════════════╗ |
||
Line 4,795: | Line 4,795: | ||
errmsg= '***error***' /*an error message eyecatcher string. */ |
errmsg= '***error***' /*an error message eyecatcher string. */ |
||
if arg() \== 0 then say errmsg "the YEARFUNC function won't accept arguments." |
if arg() \== 0 then say errmsg "the YEARFUNC function won't accept arguments." |
||
return left( date('Sorted'), 3)</ |
return left( date('Sorted'), 3)</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Calling a function with a fixed number of arguments. ║ |
║ Calling a function with a fixed number of arguments. ║ |
||
║ ║ |
║ ║ |
||
Line 4,822: | Line 4,822: | ||
end |
end |
||
return a1 + a2 + a3 + a4</ |
return a1 + a2 + a3 + a4</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Calling a function with optional arguments. ║ |
║ Calling a function with optional arguments. ║ |
||
║ ║ |
║ ║ |
||
Line 4,842: | Line 4,842: | ||
end /*j*/ |
end /*j*/ |
||
return $</ |
return $</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Calling a function with a variable number of arguments. ║ |
║ Calling a function with a variable number of arguments. ║ |
||
║ ║ |
║ ║ |
||
Line 4,871: | Line 4,871: | ||
call value 'COMMON.'name,val |
call value 'COMMON.'name,val |
||
end |
end |
||
return arg()</ |
return arg()</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Calling a function in statement context. ║ |
║ Calling a function in statement context. ║ |
||
║ ║ |
║ ║ |
||
Line 4,889: | Line 4,889: | ||
yr= yearFunc() + 20 |
yr= yearFunc() + 20 |
||
say 'two decades from now, the year will be:' yr |
say 'two decades from now, the year will be:' yr |
||
exit /*stick a fork in it, we're all done. */</ |
exit /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Obtaining the return value of a function. ║ |
║ Obtaining the return value of a function. ║ |
||
║ ║ |
║ ║ |
||
Line 4,902: | Line 4,902: | ||
call yearFunc |
call yearFunc |
||
say 'the current year is' result /*result can be RESULT, it is caseless.*/</ |
say 'the current year is' result /*result can be RESULT, it is caseless.*/</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Distinguishing built-in functions and user-defined functions. ║ |
║ Distinguishing built-in functions and user-defined functions. ║ |
||
║ ║ |
║ ║ |
||
Line 4,922: | Line 4,922: | ||
date: return 4 /*Bob only "went out" 4 times, no need */ |
date: return 4 /*Bob only "went out" 4 times, no need */ |
||
/* to actually count, he quit after 4. */</ |
/* to actually count, he quit after 4. */</syntaxhighlight> |
||
< |
<syntaxhighlight lang=rexx> /*╔════════════════════════════════════════════════════════════════════╗ |
||
║ Distinguishing subroutines and functions. ║ |
║ Distinguishing subroutines and functions. ║ |
||
║ ║ |
║ ║ |
||
Line 4,948: | Line 4,948: | ||
║ are: map (f 1 9) [1..9] ║ |
║ are: map (f 1 9) [1..9] ║ |
||
║ or: map (f(1,_,9)) [1, ..., 9] ║ |
║ or: map (f(1,_,9)) [1, ..., 9] ║ |
||
╚════════════════════════════════════════════════════════════════════╝*/</ |
╚════════════════════════════════════════════════════════════════════╝*/</syntaxhighlight> |
||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang=rexx>/* REXX *************************************************************** |
||
* 29.07.2013 Walter Pachl trying to address the task concisely |
* 29.07.2013 Walter Pachl trying to address the task concisely |
||
*********************************************************************** |
*********************************************************************** |
||
Line 5,027: | Line 5,027: | ||
If sigl=39 Then |
If sigl=39 Then |
||
Say 'fb cannot be invoked as function (it does not return a value' |
Say 'fb cannot be invoked as function (it does not return a value' |
||
Exit</ |
Exit</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,067: | Line 5,067: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang=ring> |
||
hello() |
hello() |
||
func hello |
func hello |
||
see "Hello from function" + nl |
see "Hello from function" + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=ring> |
||
first() second() |
first() second() |
||
func first see "message from the first function" + nl |
func first see "message from the first function" + nl |
||
func second see "message from the second function" + nl |
func second see "message from the second function" + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=ring> |
||
sum(3,5) sum(1000,2000) |
sum(3,5) sum(1000,2000) |
||
func sum x,y see x+y+nl |
func sum x,y see x+y+nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang=ring> |
||
# this program will print the hello world message first then execute the main function |
# this program will print the hello world message first then execute the main function |
||
See "Hello World!" + nl |
See "Hello World!" + nl |
||
func main |
func main |
||
see "Message from the main function" + nl |
see "Message from the main function" + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Line 5,095: | Line 5,095: | ||
*Calling a function that requires no arguments |
*Calling a function that requires no arguments |
||
:< |
:<syntaxhighlight lang=ruby>def foo() p "foo" end |
||
foo #=> "foo" |
foo #=> "foo" |
||
foo() #=> "foo"</ |
foo() #=> "foo"</syntaxhighlight> |
||
*Calling a function with a fixed number of arguments |
*Calling a function with a fixed number of arguments |
||
:< |
:<syntaxhighlight lang=ruby>def foo arg; p arg end # one argument |
||
foo(1) #=> 1 |
foo(1) #=> 1 |
||
foo "1" #=> "1" |
foo "1" #=> "1" |
||
foo [0,1,2] #=> [0, 1, 2] (one Array)</ |
foo [0,1,2] #=> [0, 1, 2] (one Array)</syntaxhighlight> |
||
*Calling a function with optional arguments |
*Calling a function with optional arguments |
||
:< |
:<syntaxhighlight lang=ruby>def foo(x=0, y=x, flag=true) p [x,y,flag] end |
||
foo #=> [0, 0, true] |
foo #=> [0, 0, true] |
||
foo(1) #=> [1, 1, true] |
foo(1) #=> [1, 1, true] |
||
foo(1,2) #=> [1, 2, true] |
foo(1,2) #=> [1, 2, true] |
||
foo 1,2,false #=> [1, 2, false]</ |
foo 1,2,false #=> [1, 2, false]</syntaxhighlight> |
||
*Calling a function with a variable number of arguments |
*Calling a function with a variable number of arguments |
||
:< |
:<syntaxhighlight lang=ruby>def foo(*args) p args end |
||
foo #=> [] |
foo #=> [] |
||
foo(1,2,3,4,5) #=> [1, 2, 3, 4, 5]</ |
foo(1,2,3,4,5) #=> [1, 2, 3, 4, 5]</syntaxhighlight> |
||
*Calling a function with named arguments |
*Calling a function with named arguments |
||
:< |
:<syntaxhighlight lang=ruby>def foo(id:0, name:"", age:0) p [id, name, age] end |
||
foo(age:22, name:"Tom") #=> [0, "Tom", 22]</ |
foo(age:22, name:"Tom") #=> [0, "Tom", 22]</syntaxhighlight> |
||
*Using a function in statement context |
*Using a function in statement context |
||
Line 5,134: | Line 5,134: | ||
*Obtaining the return value of a function |
*Obtaining the return value of a function |
||
:< |
:<syntaxhighlight lang=ruby>def foo(a,b) a + b end |
||
bar = foo 10,20 |
bar = foo 10,20 |
||
Line 5,145: | Line 5,145: | ||
x,y = sum_and_product(3,5) |
x,y = sum_and_product(3,5) |
||
p x #=> 8 |
p x #=> 8 |
||
p y #=> 15</ |
p y #=> 15</syntaxhighlight> |
||
*Distinguishing built-in functions and user-defined functions |
*Distinguishing built-in functions and user-defined functions |
||
Line 5,155: | Line 5,155: | ||
::These methods are called without a receiver and thus can be called in functional form. |
::These methods are called without a receiver and thus can be called in functional form. |
||
::< |
::<syntaxhighlight lang=ruby>puts "OK!" # Kernel#puts |
||
raise "Error input" # Kernel#raise |
raise "Error input" # Kernel#raise |
||
Integer("123") # Kernel#Integer |
Integer("123") # Kernel#Integer |
||
Line 5,166: | Line 5,166: | ||
private # Module#private |
private # Module#private |
||
require # Kernel#require |
require # Kernel#require |
||
loop { } # Kernel#loop</ |
loop { } # Kernel#loop</syntaxhighlight> |
||
*Stating whether arguments are passed by value or by reference |
*Stating whether arguments are passed by value or by reference |
||
Line 5,180: | Line 5,180: | ||
::The block argument sends a closure from the calling scope to the method. |
::The block argument sends a closure from the calling scope to the method. |
||
::The block argument is always last when sending a message to a method. A block is sent to a method using <code>do ... end</code> or <code>{ ... }</code>. |
::The block argument is always last when sending a message to a method. A block is sent to a method using <code>do ... end</code> or <code>{ ... }</code>. |
||
::< |
::<syntaxhighlight lang=ruby>class Array |
||
def sum(init=0, &blk) |
def sum(init=0, &blk) |
||
if blk |
if blk |
||
Line 5,193: | Line 5,193: | ||
p ary.sum #=> 15 |
p ary.sum #=> 15 |
||
p ary.sum(''){|n| (-n).to_s} #=> "-1-2-3-4-5" |
p ary.sum(''){|n| (-n).to_s} #=> "-1-2-3-4-5" |
||
p (ary.sum do |n| n * n end) #=> 55</ |
p (ary.sum do |n| n * n end) #=> 55</syntaxhighlight> |
||
:Splat operator: |
:Splat operator: |
||
::You can turn an Array into an argument list with * (or splat) operator. |
::You can turn an Array into an argument list with * (or splat) operator. |
||
::< |
::<syntaxhighlight lang=ruby>def foo(a,b,c) p [a,b,c] end |
||
args = [1,2,3] |
args = [1,2,3] |
||
foo *args #=> [1, 2, 3] |
foo *args #=> [1, 2, 3] |
||
args = [1,2] |
args = [1,2] |
||
foo(0,*args) #=> [0, 1, 2]</ |
foo(0,*args) #=> [0, 1, 2]</syntaxhighlight> |
||
:Syntax sugar: |
:Syntax sugar: |
||
::In Ruby, many operators are actually method calls. |
::In Ruby, many operators are actually method calls. |
||
::< |
::<syntaxhighlight lang=ruby># return value substance |
||
i = 3 |
i = 3 |
||
p 1 + i #=> 4 1.+(i) |
p 1 + i #=> 4 1.+(i) |
||
Line 5,218: | Line 5,218: | ||
p a & [4,2] #=> [2] a.&([4,2]) |
p a & [4,2] #=> [2] a.&([4,2]) |
||
p "abcde"[1..3] #=> "bcd" "abcde".[](1..3) |
p "abcde"[1..3] #=> "bcd" "abcde".[](1..3) |
||
p "%2d %4s" % [1,"xyz"] #=> " 1 xyz" "%2d %4s".%([1,"xyz"])</ |
p "%2d %4s" % [1,"xyz"] #=> " 1 xyz" "%2d %4s".%([1,"xyz"])</syntaxhighlight> |
||
::Method call which was displayed in the comment is usable actually. |
::Method call which was displayed in the comment is usable actually. |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>fn main() { |
||
// Rust has a lot of neat things you can do with functions: let's go over the basics first |
// Rust has a lot of neat things you can do with functions: let's go over the basics first |
||
fn no_args() {} |
fn no_args() {} |
||
Line 5,312: | Line 5,312: | ||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
{{libheader|Scala}} |
{{libheader|Scala}} |
||
< |
<syntaxhighlight lang=Scala>def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods |
||
def myFunction0() = ??? |
def myFunction0() = ??? |
||
myFunction0() // function invoked with empty parameter list |
myFunction0() // function invoked with empty parameter list |
||
Line 5,380: | Line 5,380: | ||
// No distinction between built-in functions and user-defined functions |
// No distinction between built-in functions and user-defined functions |
||
// No distinction between subroutines and functions</ |
// No distinction between subroutines and functions</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Line 5,389: | Line 5,389: | ||
* All parameters are positional. |
* All parameters are positional. |
||
* There are no differences between between calling built-in vs. user defined functions.< |
* There are no differences between between calling built-in vs. user defined functions.<syntaxhighlight lang=seed7>env := environment; # Call a function that requires no arguments. |
||
env := environment(); # Alternative possibility to call of a function with no arguments. |
env := environment(); # Alternative possibility to call of a function with no arguments. |
||
cmp := compare(i, j); # Call a function with a fixed number of arguments.</ |
cmp := compare(i, j); # Call a function with a fixed number of arguments.</syntaxhighlight> |
||
* There are no optional arguments, but a similar effect can be achieved with overloading.< |
* There are no optional arguments, but a similar effect can be achieved with overloading.<syntaxhighlight lang=seed7>write(aFile, "asdf"); # Variant of write with a parameter to specify a file. |
||
write("asdf"); # Variant of write which writes to the file OUT.</ |
write("asdf"); # Variant of write which writes to the file OUT.</syntaxhighlight> |
||
* Seed7 does not support functions with a variable number of arguments. But a function argument can be an array with as many values as you want:< |
* Seed7 does not support functions with a variable number of arguments. But a function argument can be an array with as many values as you want:<syntaxhighlight lang=seed7>const func integer: sum (in array integer: intElems) is func |
||
result |
result |
||
var integer: sum is 0; |
var integer: sum is 0; |
||
Line 5,408: | Line 5,408: | ||
s := sum([] (1, 2, 3)); # Use an aggregate to generate an array. |
s := sum([] (1, 2, 3)); # Use an aggregate to generate an array. |
||
t := sum([] (2, 3, 5, 7));</ |
t := sum([] (2, 3, 5, 7));</syntaxhighlight> |
||
* Concatenation operators can be used to concatenate arguments. This solution is used to provide the write function:< |
* Concatenation operators can be used to concatenate arguments. This solution is used to provide the write function:<syntaxhighlight lang=seed7>write("Nr: " <& num); # Use operators to concatenate arguments.</syntaxhighlight> |
||
* The procedure ignore can be used to ignore a return value.< |
* The procedure ignore can be used to ignore a return value.<syntaxhighlight lang=seed7>ignore(getln(IN)); # Using a function in statement context (ignore the result).</syntaxhighlight> |
||
* Call-by-name parameters use a function in first-class context. The function [http://seed7.sourceforge.net/examples/map.htm doMap] from the examples section of the Seed7 homepage uses a given expression to modify the elements of an array:< |
* Call-by-name parameters use a function in first-class context. The function [http://seed7.sourceforge.net/examples/map.htm doMap] from the examples section of the Seed7 homepage uses a given expression to modify the elements of an array:<syntaxhighlight lang=seed7>seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x));</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
* If no variable is specified, `put` prints the variable to stdout |
* If no variable is specified, `put` prints the variable to stdout |
||
< |
<syntaxhighlight lang=sensetalk>put zeroArgsFn() |
||
// Function calls can also be made using the following syntax: |
// Function calls can also be made using the following syntax: |
||
Line 5,426: | Line 5,426: | ||
put "This function was run with zero arguments." |
put "This function was run with zero arguments." |
||
return "Return value from zero argument function" |
return "Return value from zero argument function" |
||
end zeroArgsFn</ |
end zeroArgsFn</syntaxhighlight> |
||
* Running a function requires a keyword such as `put; if no variable is return, put into e.g. _ |
* Running a function requires a keyword such as `put; if no variable is return, put into e.g. _ |
||
< |
<syntaxhighlight lang=sensetalk>put TwoArgFn("variable", (3, 4)) into _ |
||
// Alternatively, the function can be called like so: |
// Alternatively, the function can be called like so: |
||
Line 5,443: | Line 5,443: | ||
put "2 argument function: arg1 = " & arg1 & "; arg2 = " & arg2 |
put "2 argument function: arg1 = " & arg1 & "; arg2 = " & arg2 |
||
put "Parameters = " & the parameterList |
put "Parameters = " & the parameterList |
||
end TwoArgFn</ |
end TwoArgFn</syntaxhighlight> |
||
* A parameter is set to "" if nothing is specified |
* A parameter is set to "" if nothing is specified |
||
< |
<syntaxhighlight lang=sensetalk>get ThreeArgFn("variable", (3, 4)) |
||
function ThreeArgFn arg1, arg2, arg3 |
function ThreeArgFn arg1, arg2, arg3 |
||
put "3 argument function: arg1 = " & arg1 & "; arg2 = " & arg2 & "; arg3 = " & arg3 |
put "3 argument function: arg1 = " & arg1 & "; arg2 = " & arg2 & "; arg3 = " & arg3 |
||
end ThreeArgFn</ |
end ThreeArgFn</syntaxhighlight> |
||
* Using this, default parameter values can be set up if a check if done at the start of the function |
* Using this, default parameter values can be set up if a check if done at the start of the function |
||
< |
<syntaxhighlight lang=sensetalk>get OneArgFn() -- arg1 is 5 |
||
get OneArgFn(10) -- arg1 is now 10 |
get OneArgFn(10) -- arg1 is now 10 |
||
Line 5,461: | Line 5,461: | ||
end if |
end if |
||
put "One argument function; arg1 = " & arg1 |
put "One argument function; arg1 = " & arg1 |
||
end OneArgFn</ |
end OneArgFn</syntaxhighlight> |
||
* All variables are, by default, passed by value |
* All variables are, by default, passed by value |
||
* If the argument prefixed by 'container', the variable is passed by reference |
* If the argument prefixed by 'container', the variable is passed by reference |
||
< |
<syntaxhighlight lang=sensetalk>put 3 into a |
||
get AddOne(a) |
get AddOne(a) |
||
put "Value of a = " & a |
put "Value of a = " & a |
||
Line 5,477: | Line 5,477: | ||
function AddOne n |
function AddOne n |
||
add 1 to n |
add 1 to n |
||
end AddOne</ |
end AddOne</syntaxhighlight> |
||
SenseTalk also distinguishes between functions and subroutines, which it calls handlers: |
SenseTalk also distinguishes between functions and subroutines, which it calls handlers: |
||
< |
<syntaxhighlight lang=sensetalk>CustomHandler 1, 2, 3 |
||
// Prints: 1 - 2 - 3 |
// Prints: 1 - 2 - 3 |
||
to handle CustomHandler arg1, arg2, arg3 |
to handle CustomHandler arg1, arg2, arg3 |
||
put arg1 && "-" && arg2 && "-" && arg3 |
put arg1 && "-" && arg2 && "-" && arg3 |
||
end CustomHandler</ |
end CustomHandler</syntaxhighlight> |
||
Subroutines can be called as a command, without storing the output |
Subroutines can be called as a command, without storing the output |
||
< |
<syntaxhighlight lang=sensetalk> |
||
MyCommand 1, "variable", (4, 5, 6) |
MyCommand 1, "variable", (4, 5, 6) |
||
Line 5,494: | Line 5,494: | ||
... |
... |
||
end MyCommand |
end MyCommand |
||
</syntaxhighlight> |
|||
</lang> |
|||
Functions/subroutines can also be defined with the to, on or function keywords: |
Functions/subroutines can also be defined with the to, on or function keywords: |
||
< |
<syntaxhighlight lang=sensetalk>to MyFn args |
||
... |
... |
||
end MyFn |
end MyFn |
||
Line 5,508: | Line 5,508: | ||
... |
... |
||
end args |
end args |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
All functions in Sidef are first-class closures |
All functions in Sidef are first-class closures |
||
< |
<syntaxhighlight lang=ruby>foo(); # without arguments |
||
foo(1, 2); # with two arguments |
foo(1, 2); # with two arguments |
||
foo(args...); # with a variable number of arguments |
foo(args...); # with a variable number of arguments |
||
Line 5,521: | Line 5,521: | ||
var arr = [1,2,3]; |
var arr = [1,2,3]; |
||
foo(arr); # the arguments are passed by object-reference</ |
foo(arr); # the arguments are passed by object-reference</syntaxhighlight> |
||
Partial application is possible by using a curry function: |
Partial application is possible by using a curry function: |
||
< |
<syntaxhighlight lang=ruby>func curry(f, *args1) { |
||
func (*args2) { |
func (*args2) { |
||
f(args1..., args2...); |
f(args1..., args2...); |
||
Line 5,536: | Line 5,536: | ||
var adder = curry(add, 1); |
var adder = curry(add, 1); |
||
say adder(3); #=>4</ |
say adder(3); #=>4</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Where f is a closure and arguments is an array of values for f to operate on. |
Where f is a closure and arguments is an array of values for f to operate on. |
||
<lang |
<syntaxhighlight lang=smalltalk>f valueWithArguments: arguments.</syntaxhighlight> |
||
=={{header|SSEM}}== |
=={{header|SSEM}}== |
||
Line 5,546: | Line 5,546: | ||
This code fragment, beginning (for the sake of argument) at address 10, performs a Wheeler jump to a subroutine beginning at address 20. The return address is coded in negative (two's complement) form because the SSEM negates values in the process of loading them into the accumulator. As always on the SSEM, jump targets are one less than the actual intended target: this is because the CI ("Current Instruction") register is incremented after an instruction has been executed rather than before. |
This code fragment, beginning (for the sake of argument) at address 10, performs a Wheeler jump to a subroutine beginning at address 20. The return address is coded in negative (two's complement) form because the SSEM negates values in the process of loading them into the accumulator. As always on the SSEM, jump targets are one less than the actual intended target: this is because the CI ("Current Instruction") register is incremented after an instruction has been executed rather than before. |
||
< |
<syntaxhighlight lang=ssem>00110000000000100000000000000000 10. -12 to c |
||
10110000000000000000000000000000 11. 13 to CI |
10110000000000000000000000000000 11. 13 to CI |
||
11001111111111111111111111111111 12. -13 |
11001111111111111111111111111111 12. -13 |
||
11001000000000000000000000000000 13. 19</ |
11001000000000000000000000000000 13. 19</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang=Swift>// call a function with no args |
||
noArgs() |
noArgs() |
||
Line 5,586: | Line 5,586: | ||
// getting a bunch of return values, discarding second returned value |
// getting a bunch of return values, discarding second returned value |
||
let (foo, _, baz) = returnSomeValues()</ |
let (foo, _, baz) = returnSomeValues()</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang=tcl>aCallToACommandWithNoArguments |
||
aCallToACommandWithOne argument |
aCallToACommandWithOne argument |
||
aCallToACommandWith arbitrarily many arguments |
aCallToACommandWith arbitrarily many arguments |
||
Line 5,595: | Line 5,595: | ||
aCallToACommandWith -oneNamed argument -andAnother namedArgument |
aCallToACommandWith -oneNamed argument -andAnother namedArgument |
||
aCallToACommandWith theNameOfAnotherCommand |
aCallToACommandWith theNameOfAnotherCommand |
||
aCallToOneCommand [withTheResultOfAnother]</ |
aCallToOneCommand [withTheResultOfAnother]</syntaxhighlight> |
||
Tcl does differentiate between functions and other types of commands in expressions: |
Tcl does differentiate between functions and other types of commands in expressions: |
||
< |
<syntaxhighlight lang=tcl>expr {func() + [cmd]} |
||
expr {func(1,2,3} + [cmd a b c]}</ |
expr {func(1,2,3} + [cmd a b c]}</syntaxhighlight> |
||
However, there are no deep differences between the two: functions are translated into commands that are called in a particular namespace (thus <tt>foo()</tt> becomes <tt>tcl::mathfunc::foo</tt>). |
However, there are no deep differences between the two: functions are translated into commands that are called in a particular namespace (thus <tt>foo()</tt> becomes <tt>tcl::mathfunc::foo</tt>). |
||
There are no differences in usage between built-in commands and user-defined ones, and parameters are passed to commands by value conceptually (and read-only reference in the implementation). |
There are no differences in usage between built-in commands and user-defined ones, and parameters are passed to commands by value conceptually (and read-only reference in the implementation). |
||
Line 5,605: | Line 5,605: | ||
=={{header|True BASIC}}== |
=={{header|True BASIC}}== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang=qbasic>FUNCTION Copialo$ (txt$, siNo, final$) |
||
FOR cont = 1 TO ROUND(siNo) |
FOR cont = 1 TO ROUND(siNo) |
||
LET nuevaCadena$ = nuevaCadena$ & txt$ |
LET nuevaCadena$ = nuevaCadena$ & txt$ |
||
Line 5,635: | Line 5,635: | ||
PRINT |
PRINT |
||
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'") |
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'") |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,646: | Line 5,646: | ||
In the shell, there are no argument specifications for functions. Functions obtain their arguments using the positional parameter facilities and functions are simply called by name followed by any arguments that are to be passed: |
In the shell, there are no argument specifications for functions. Functions obtain their arguments using the positional parameter facilities and functions are simply called by name followed by any arguments that are to be passed: |
||
< |
<syntaxhighlight lang=sh>sayhello # Call a function in statement context with no arguments |
||
multiply 3 4 # Call a function in statement context with two arguments</ |
multiply 3 4 # Call a function in statement context with two arguments</syntaxhighlight> |
||
The shell does not support the use of named parameters. There is no lookahead in the shell, so functions cannot be called until their definition has been run. |
The shell does not support the use of named parameters. There is no lookahead in the shell, so functions cannot be called until their definition has been run. |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang=vb>'definitions/declarations |
||
'Calling a function that requires no arguments |
'Calling a function that requires no arguments |
||
Line 5,781: | Line 5,781: | ||
End Sub |
End Sub |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre>no arguments ok |
<pre>no arguments ok |
||
no arguments ok |
no arguments ok |
||
Line 5,799: | Line 5,799: | ||
=={{header|WDTE}}== |
=={{header|WDTE}}== |
||
< |
<syntaxhighlight lang=wdte>let noargs => + 2 5; |
||
noargs -- print; |
noargs -- print; |
||
Line 5,818: | Line 5,818: | ||
# evaluates `+ 3` and then passes 7 to the resulting partially applied |
# evaluates `+ 3` and then passes 7 to the resulting partially applied |
||
# function. |
# function. |
||
(+ 3) 7 -- print;</ |
(+ 3) 7 -- print;</syntaxhighlight> |
||
=={{header|WebAssembly}}== |
=={{header|WebAssembly}}== |
||
< |
<syntaxhighlight lang=webassembly>(func $main (export "_start") |
||
(local $result i32) |
(local $result i32) |
||
Line 5,852: | Line 5,852: | ||
(i32.const 8) |
(i32.const 8) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Line 5,881: | Line 5,881: | ||
Here are some examples: |
Here are some examples: |
||
< |
<syntaxhighlight lang=ecmascript>var f1 = Fn.new { System.print("Function 'f1' with no arguments called.") } |
||
var f2 = Fn.new { |a, b| |
var f2 = Fn.new { |a, b| |
||
System.print("Function 'f2' with 2 arguments called and passed %(a) & %(b).") |
System.print("Function 'f2' with 2 arguments called and passed %(a) & %(b).") |
||
Line 5,913: | Line 5,913: | ||
mc1.x = 42 // change mc1's field using setter |
mc1.x = 42 // change mc1's field using setter |
||
System.print(-mc1.x) // invoke prefix operator - |
System.print(-mc1.x) // invoke prefix operator - |
||
System.print(mc1 + mc2) // invoke infix operator +</ |
System.print(mc1 + mc2) // invoke infix operator +</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,927: | Line 5,927: | ||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
< |
<syntaxhighlight lang=lisp>; call a function (procedure) with no arguments: |
||
(foo) |
(foo) |
||
Line 5,945: | Line 5,945: | ||
; or it can simply be discarded |
; or it can simply be discarded |
||
(foo bar) |
(foo bar) |
||
; nothing is done with the return value</ |
; nothing is done with the return value</syntaxhighlight> |
||
=={{header|XSLT}}== |
=={{header|XSLT}}== |
||
< |
<syntaxhighlight lang=xml><?xml version="1.0" encoding="UTF-8"?> |
||
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> |
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> |
||
<xsl:output method="xml" indent="yes"/> |
<xsl:output method="xml" indent="yes"/> |
||
Line 6,226: | Line 6,226: | ||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet> |
</xsl:stylesheet> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang=Yabasic> |
||
sub test(a, b, c) : print a, b, c : end sub |
sub test(a, b, c) : print a, b, c : end sub |
||
Line 6,247: | Line 6,247: | ||
test$("1, 2, 3, 4, text, 6, 7, 8, \"include text\"") |
test$("1, 2, 3, 4, text, 6, 7, 8, \"include text\"") |
||
print</ |
print</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Line 6,253: | Line 6,253: | ||
Using f has a function, method or object: |
Using f has a function, method or object: |
||
< |
<syntaxhighlight lang=zkl>f(); f(1,2,3,4); |
||
fcn f(a=1){}() // define and call f, which gets a set to 1 |
fcn f(a=1){}() // define and call f, which gets a set to 1 |
||
fcn{vm.arglist}(1,2,3,4) // arglist is L(1,2,3,4) |
fcn{vm.arglist}(1,2,3,4) // arglist is L(1,2,3,4) |
||
Line 6,262: | Line 6,262: | ||
s:=f() |
s:=f() |
||
fcn{}.isType(self.fcn) //True |
fcn{}.isType(self.fcn) //True |
||
fcn{}.len.isType(self.fcn) //False, len is a Method</ |
fcn{}.len.isType(self.fcn) //False, len is a Method</syntaxhighlight> |
||
Partial application is done with the .fp* methods or the 'wrap keyword |
Partial application is done with the .fp* methods or the 'wrap keyword |
||
< |
<syntaxhighlight lang=zkl> |
||
fcn(a,b,c).fp(1)() // call function with a always set to 1 |
fcn(a,b,c).fp(1)() // call function with a always set to 1 |
||
fcn(a,b,c).fp1(2,3)() // call function with b & c always set to 2 & 3 |
fcn(a,b,c).fp1(2,3)() // call function with b & c always set to 2 & 3 |
||
Line 6,274: | Line 6,274: | ||
a:=5; f('wrap(b){a+b}) // 'wrap is syntactic sugar for .fpN |
a:=5; f('wrap(b){a+b}) // 'wrap is syntactic sugar for .fpN |
||
// to create a lexical closure --> f(fcn(b,a){a+b}.fpN(1,a))</ |
// to create a lexical closure --> f(fcn(b,a){a+b}.fpN(1,a))</syntaxhighlight> |
||
=={{header|zonnon}}== |
=={{header|zonnon}}== |
||
< |
<syntaxhighlight lang=zonnon> |
||
module CallingProcs; |
module CallingProcs; |
||
type |
type |
||
Line 6,333: | Line 6,333: | ||
writeln(total); |
writeln(total); |
||
end CallingProcs. |
end CallingProcs. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
Line 6,341: | Line 6,341: | ||
* Functions that take a fixed number of arguments usually require the programmer to load the arguments into registers or push them to the stack prior to calling the function. |
* Functions that take a fixed number of arguments usually require the programmer to load the arguments into registers or push them to the stack prior to calling the function. |
||
< |
<syntaxhighlight lang=z80>PackNibbles: |
||
;input: B = top nibble, C = bottom nibble. Outputs to accumulator. |
;input: B = top nibble, C = bottom nibble. Outputs to accumulator. |
||
;usage: B = &0X, C = &0Y, => A = &XY |
;usage: B = &0X, C = &0Y, => A = &XY |
||
Line 6,351: | Line 6,351: | ||
RLCA |
RLCA |
||
OR C |
OR C |
||
RET</ |
RET</syntaxhighlight> |
||
* Assembly language in general has difficulty with optional and variable numbers of arguments (unless it is written by a compiler, of course). Prior to the function call, an optional argument would most likely be set to zero if intended to be unused in a particular instance of a function. |
* Assembly language in general has difficulty with optional and variable numbers of arguments (unless it is written by a compiler, of course). Prior to the function call, an optional argument would most likely be set to zero if intended to be unused in a particular instance of a function. |
||
Line 6,361: | Line 6,361: | ||
* Getting a function's return value depends on how it was programmed. The concept of "return values" is a high-level construct that isn't enforced by assembly languages in general, and Z80 is no exception. The programmer is free to choose which register or section of memory the return value of a function is stored, if one even exists. Generally speaking the accumulator is usually used for this purpose but it depends on the data type as well as the needs of the program. |
* Getting a function's return value depends on how it was programmed. The concept of "return values" is a high-level construct that isn't enforced by assembly languages in general, and Z80 is no exception. The programmer is free to choose which register or section of memory the return value of a function is stored, if one even exists. Generally speaking the accumulator is usually used for this purpose but it depends on the data type as well as the needs of the program. |
||
< |
<syntaxhighlight lang=z80>AddTwoNumbers |
||
;input registers: A,B. Outputs to A. |
;input registers: A,B. Outputs to A. |
||
ADD a,b |
ADD a,b |
||
RET</ |
RET</syntaxhighlight> |
||
* Some implementations of Z80 Assembly have built-in functions. These are essentially just subroutines located in ROM at a specific memory address. Functions stored in low memory can be called with the <code>RST #</code> instruction. Anything in high memory will need to be <code>CALL</code>ed like any other user-created subroutine. On the Amstrad CPC, <code>CALL &BB5A</code> will print the accumulator to the screen as an ASCII character. |
* Some implementations of Z80 Assembly have built-in functions. These are essentially just subroutines located in ROM at a specific memory address. Functions stored in low memory can be called with the <code>RST #</code> instruction. Anything in high memory will need to be <code>CALL</code>ed like any other user-created subroutine. On the Amstrad CPC, <code>CALL &BB5A</code> will print the accumulator to the screen as an ASCII character. |
||
Line 6,374: | Line 6,374: | ||
On the ZX Spectrum, functions and subroutines are separate entities. A function is limited to being a single expression that generates a return value. Statements are not allowed within a function. A subroutine can perform input and output and can contain statements. |
On the ZX Spectrum, functions and subroutines are separate entities. A function is limited to being a single expression that generates a return value. Statements are not allowed within a function. A subroutine can perform input and output and can contain statements. |
||
< |
<syntaxhighlight lang=zxbasic>10 REM functions cannot be called in statement context |
||
20 PRINT FN a(5): REM The function is used in first class context. Arguments are not named |
20 PRINT FN a(5): REM The function is used in first class context. Arguments are not named |
||
30 PRINT FN b(): REM Here we call a function that has no arguments |
30 PRINT FN b(): REM Here we call a function that has no arguments |
||
Line 6,385: | Line 6,385: | ||
100 PRINT SIN(50): REM here we pass a parameter to a builtin function |
100 PRINT SIN(50): REM here we pass a parameter to a builtin function |
||
110 PRINT RND(): REM here we use a builtin function without parameters |
110 PRINT RND(): REM here we use a builtin function without parameters |
||
120 RANDOMIZE: REM statements are not functions and cannot be used in first class context.</ |
120 RANDOMIZE: REM statements are not functions and cannot be used in first class context.</syntaxhighlight> |
||
{{omit from|GUISS}} |
{{omit from|GUISS}} |