Call a function: Difference between revisions

102,206 bytes added ,  22 days ago
m
 
(112 intermediate revisions by 47 users not shown)
Line 1:
{{task}}[[Category:Functions and subroutines]]
[[Category:Simple]]
{{task}}
 
;Task:
Line 23 ⟶ 24:
This task is ''not'' about [[Function definition|defining functions]].
<br><bR>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F no_args() {}
// call
no_args()
 
F fixed_args(x, y)
print(‘x=#., y=#.’.format(x, y))
// call
fixed_args(1, 2) // x=1, y=2
 
// named arguments
fixed_args(x' 1, y' 2)
 
F opt_args(x = 1)
print(x)
// calls
opt_args() // 1
opt_args(3.141) // 3.141</syntaxhighlight>
=={{header|360 Assembly}}==
Due to assembler, argument are passed by reference.<br>
With:
<langsyntaxhighlight lang="360asm">X DS F
Y DS F
Z DS F</langsyntaxhighlight>
If you do not want to use the CALL macro instruction and for a link-edited object-module:
<langsyntaxhighlight lang="360asm"> L R15,=V(MULTPLIC)
LA R1,PARMLIST address of the paramter list
BALR R14,R15 branch and link
Line 37 ⟶ 57:
* ...
PARMLIST DC A(X)
DC A(Y)</langsyntaxhighlight>
If you call a link-edited object-module:
<langsyntaxhighlight lang="360asm"> CALL MULTPLIC,(X,Y) call MULTPLIC(X,Y)
ST R0,Z Z=MULTPLIC(X,Y)</langsyntaxhighlight>
If you call an load-module at execution time:
<langsyntaxhighlight lang="360asm"> LOAD EP=MULTPLIC load load-module
LR R15,R0 retrieve entry address
CALL (R15),(X,Y) call MULTPLIC(X,Y)
ST R0,Z Z=MULTPLIC(X,Y)</langsyntaxhighlight>
=={{header|6502 Assembly}}==
 
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.
 
<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.
<syntaxhighlight lang="6502asm">sum:
;adds the values in zero page address $00 and $01, outputs to accumulator.
LDA $00 ;load the byte stored at memory address $0000
CLC
ADC $01 ;add the byte at memory address $0001
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.
 
Statements like <code>PRINT SIN(45)</code>, or expressions where you assign a variable to a function's output don't exist in assembly. You have to perform the functions individually, working from the inside out, and process them one at a time. In other words, a BASIC statement like <code>PRINT SIN(45)</code> would have to compute <code>SIN(45)</code> first, then pass the return value to <code>PRINT</code>. This is just as true with modern CPUs as it was with the 6502.
 
The closest thing 6502 has to true "built-in functions" are the interrupt vectors whose pointers are stored at the very end of memory. They are, in order: Non-maskable interrupt (NMI), reset, and IRQ (Interrupt Request). They are no different than other functions except they end in <code>RTI</code> rather than <code>RTS</code>. With "bare-metal programming" like on the NES this is all you have, but most computers of the 80s had some sort of kernel or operating system that had pre-defined functions you could use simply by <code>JSR</code>ing their memory address. The actual memory locations of these, and what they did, varies by implementation.
=={{header|8086 Assembly}}==
 
A function that requires no arguments is simply <code>CALL</code>ed:
<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.
 
<syntaxhighlight lang="asm">push ax ;second argument
push bx ;first argument - typically arguments are pushed in the reverse order they are listed.
call foo
pop bx
pop ax
 
foo:
push bp
mov bp,sp
;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.
 
<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</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:
<syntaxhighlight lang="asm">mov AH,4Ch
mov AL,00h
int 21h</syntaxhighlight>
=={{header|68000 Assembly}}==
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.
 
<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.
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program callfonct.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/***********************/
/* Initialized data */
/***********************/
.data
szMessage: .asciz "Hello. \n" // message
szRetourLigne: .asciz "\n"
szMessResult: .asciz "Resultat : " // message result
 
/***********************/
/* No Initialized data */
/***********************/
.bss
sZoneConv: .skip 100
 
.text
.global main
main:
ldr x0,=szMessage // adresse of message short program
bl affichageMess // call function with 1 parameter (x0)
 
// call function with parameters in register
mov x0,#5
mov x1,#10
bl fonction1 // call function with 2 parameters (x0,x1)
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,=szMessResult
bl affichageMess // call function with 1 parameter (x0)
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
// call function with parameters on stack
mov x0,#5
mov x1,#10
stp x0,x1,[sp,-16]! // store registers on stack
bl fonction2 // call function with 2 parameters on the stack
// result in x0
ldr x1,qAdrsZoneConv
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,=szMessResult
bl affichageMess // call function with 1 parameter (x0)
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
// end of program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszRetourLigne: .quad szRetourLigne
/******************************************************************/
/* call function parameter in register */
/******************************************************************/
/* x0 value one */
/* x1 value two */
/* return in x0 */
fonction1:
stp x2,lr,[sp,-16]! // save registers
mov x2,#20
mul x0,x0,x2
add x0,x0,x1
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
 
/******************************************************************/
/* call function parameter in the stack */
/******************************************************************/
/* return in x0 */
fonction2:
stp fp,lr,[sp,-16]! // save registers
add fp,sp,#16 // address parameters in the stack
stp x1,x2,[sp,-16]! // save others registers
ldr x0,[fp] // second paraméter
ldr x1,[fp,#8] // first parameter
mov x2,#-20
mul x0,x0,x2
add x0,x0,x1
ldp x1,x2,[sp],16 // restaur 2 registres
ldp fp,lr,[sp],16 // restaur 2 registres
add sp,sp,#16 // very important, for stack aligned
ret // retour adresse lr x30
 
 
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{output}}
<pre>
Hello.
Resultat : +110
Resultat : -90
</pre>
=={{header|ActionScript}}==
 
<langsyntaxhighlight lang="actionscript"> myfunction(); /* function with no arguments in statement context */
myfunction(6,b); // function with two arguments in statement context
stringit("apples"); //function with a string argument</langsyntaxhighlight>
 
=={{header|Ada}}==
 
Line 61 ⟶ 241:
* 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!):<syntaxhighlight lang Ada="ada">S: String := Ada.Text_IO.Get_Line;</langsyntaxhighlight>
 
* Ada supports functions with optional parameters:<langsyntaxhighlight Adalang="ada">function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional
...
A : Integer := F(12);
B : Integer := F(12, 0); -- the same as A
C : Integer := F(12, 1); -- something different</langsyntaxhighlight>
 
* 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:<langsyntaxhighlight Adalang="ada">type Integer_Array is array (Positive range <>) of Integer;
function Sum(A: Integer_Array) return Integer is
S: Integer := 0;
Line 82 ⟶ 262:
...
A := Sum((1,2,3)); -- A = 6
B := Sum((1,2,3,4)); -- B = 10</langsyntaxhighlight>
 
* One can realize first-class functions by defining an access to a function as a parameter:<langsyntaxhighlight Adalang="ada">function H (Int: Integer;
Fun: not null access function (X: Integer; Y: Integer)
return Integer);
Line 92 ⟶ 272:
 
X := H(A, F'Access) -- assuming X and A are Integers, and F is a function
-- taking two Integers and returning an Integer.</langsyntaxhighlight>
 
* The caller is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first) <langsyntaxhighlight Adalang="ada">Positional := H(A, F'Access);
Named := H(Int => A, Fun => F'Access);
Mixed := H(A, Fun=>F'Access); </langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># Note functions and subroutines are called procedures (or PROCs) in Algol 68 #
# A function called without arguments: #
f;
Line 137 ⟶ 316:
# If the function is declared with argument(s) of mode REF MODE,
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... #</langsyntaxhighlight>
 
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 143 ⟶ 322:
See [http://rosettacode.org/wiki/Optional_parameters#ALGOL_68 Optional Parameters] for an example of optional parameters in Algol 68.<br>
See [http://rosettacode.org/wiki/Named_parameters#ALGOL_68 Named Parameters] for an example of named parameters in Algol 68.
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">% Note, in Algol W, functions are called procedures %
% calling a function with no parameters: %
f;
Line 182 ⟶ 360:
% parameters are somewhat like macros %
 
% Partial application is not possible in Algol W %</langsyntaxhighlight>
 
=={{header|AntLang}}==
AntLang provides two ways to apply a function.
One way is infix application.
<syntaxhighlight lang AntLang="antlang">2*2+9</langsyntaxhighlight>
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.
The other way is prefix application.
<langsyntaxhighlight AntLanglang="antlang">*[2;+[2;9]]
echo["Hello!"]
time[]</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 371 ⟶ 547:
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
</lang>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">printHello: $[][
print "Hello World!"
]
 
sayHello: $[name][
print ["Hello" name "!"]
]
 
printAll: $[args][
loop args [arg][
print arg
]
]
 
getNumber: $[][3]
 
; Calling a function that requires no arguments
printHello
 
; Calling a function with a fixed number of arguments
sayHello "John"
 
; Calling a function with a variable number of arguments
printAll ["one" "two" "three"]
 
; Using a function in statement context
if true [printHello]
print getNumber
 
; Using a function in first-class context within an expression
if getNumber=3 [print "yep, it worked"]
 
; Obtaining the return value of a function:
num: getNumber
 
print num
</syntaxhighlight>
{{out}}
 
<pre>Hello World!
Hello John !
one
two
three
Hello World!
3
yep, it worked
3</pre>
=={{header|AutoHotkey}}==
<langsyntaxhighlight AHKlang="ahk">; Call a function without arguments:
f()
 
Line 413 ⟶ 638:
 
; Partial application is impossible.
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
 
The awk interpreter reads the entire script prior to processing, so functions can be called from sections of code appearing before the definition.
 
<langsyntaxhighlight lang="awk">BEGIN {
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
}</langsyntaxhighlight>
 
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.
 
The awk extraction and reporting language does not support the use of named parameters.
 
=={{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.
<langsyntaxhighlight lang="axe">NOARG()
ARGS(1,5,42)</langsyntaxhighlight>
 
Since arguments are simply global variables, they are always optional and can be omitted from right to left.
<langsyntaxhighlight lang="axe">OPARG(1,2,3,4,5,6)
OPARG(1,2,3)
OPARG()</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="axe">MATHS(2,4)→A
Disp GETSTR()</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="axe">USER()
axeFunc()</langsyntaxhighlight>
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">function Copialo$ (txt$, siNo, final$)
nuevaCadena$ = ""
 
for cont = 1 to siNo
nuevaCadena$ += txt$
next cont
 
return trim(nuevaCadena$) + final$
end function
 
subroutine Saludo()
print "Hola mundo!"
end subroutine
 
subroutine testCadenas (txt$)
for cont = 1 to length(txt$)
print mid(txt$, cont, 1); "";
next cont
end subroutine
 
subroutine testNumeros (a, b, c)
print a, b, c
end subroutine
 
call Saludo()
print Copialo$("Saludos ", 6, "")
print Copialo$("Saludos ", 3, "!!")
print
call testNumeros(1, 2, 3)
call testNumeros(1, 2, 0)
print
call testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \#incluye texto\#")
end</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
=={{header|Batch File}}==
Line 450 ⟶ 713:
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.
 
<langsyntaxhighlight lang="dos">
:: http://rosettacode.org/wiki/Call_a_function
:: Demonstrate the different syntax and semantics provided for calling a function.
Line 537 ⟶ 800:
endlocal & echo.%filepath%%filename%
goto:eof
</syntaxhighlight>
</lang>
Output:
<pre>
Line 558 ⟶ 821:
C:\Test Directory\test.file
</pre>
 
=={{header|BBC BASIC}}==
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:
<syntaxhighlight lang ="bbcbasic">PRINT SQR(2)</langsyntaxhighlight>
The parentheses can often be omitted:
<syntaxhighlight lang ="bbcbasic">PRINT SQR 2</langsyntaxhighlight>
The name of a <b>user-defined function</b> must begin with <tt>FN</tt>. A call to it is also an expression:
<langsyntaxhighlight lang="bbcbasic">PRINT FN_foo(bar$, baz%)</langsyntaxhighlight>
(The sigils <tt>$</tt> and <tt>%</tt> identify the variables' types.)
A function that takes no arguments can be called omitting the parentheses:
<syntaxhighlight lang ="bbcbasic">PRINT FN_foo</langsyntaxhighlight>
The name of a <b>procedure</b> must begin with <tt>PROC</tt>. A call to it is a statement, not an expression:
<syntaxhighlight lang ="bbcbasic">PROC_foo</langsyntaxhighlight>
If it has arguments, they come in parentheses just as with a function:
<langsyntaxhighlight lang="bbcbasic">PROC_foo(bar$, baz%, quux)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="bbcbasic">DEF PROC_foo(a$, RETURN b%, RETURN c)</langsyntaxhighlight>
<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.
<syntaxhighlight lang ="bbcbasic">200 GOSUB 30050</langsyntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
 
Function calling is the sole primitive in the Lambda Calculus. The application of function f on argument a is denoted 01 f a in Binary Lambda Calculus. Multi argument functions are achieved by currying, i.e. a function of the first argument returns a function of the 2nd argument, etc. A good example is the Church numeral 2, which given a function f and an argument x, applies f twice on x: C2 = \f. \x. f (f x). This is written in BLC as
 
<pre>00 00 01 110 01 110 01</pre>
 
=={{header|BQN}}==
 
BQN's functions take one or two arguments, and the behave like the primitive functions of the language.
 
'''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.
 
'''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>:
 
<syntaxhighlight lang="bqn">F 1</syntaxhighlight> is an example of a single argument call.
 
<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 a variable number of arguments:''' A function supporting variable arguments can be made by taking an array as any of the arguments.
 
'''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
}</syntaxhighlight>
 
Given a three element array, the above example will concatenate them all together.
 
'''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.
 
<syntaxhighlight lang="bqn">1 {𝕨+𝕩} 2</syntaxhighlight>
is the same as
<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.
 
<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.
 
'''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.
 
'''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.
 
<syntaxhighlight lang="bqn">+⟜2</syntaxhighlight> will add two to the number given to it.
<syntaxhighlight lang="bqn">2⊸-</syntaxhighlight> will subtract its input from two.
=={{header|Bracmat}}==
 
Line 585 ⟶ 903:
Strictly speaking, all Bracmat functions receive at least one argument. But empty strings are valid expressions, so you can do
 
<syntaxhighlight lang ="bracmat">aFunctionWithoutArguments$</langsyntaxhighlight>
or
<syntaxhighlight lang ="bracmat">aFunctionWithoutArguments'</langsyntaxhighlight>
 
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 614 ⟶ 932:
 
You can do
<syntaxhighlight lang ="bracmat">func$!myargument;</langsyntaxhighlight>
The <code>;</code> marks the end of a Bracmat statement.
 
Line 621 ⟶ 939:
(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
 
<langsyntaxhighlight lang="bracmat">(yourfunc=local vars.function body)</langsyntaxhighlight>
If there is already a function <code>myfunc</code> that you want to assign to <code>yourfunc</code> as well, do
<langsyntaxhighlight lang="bracmat">('$myfunc:(=?yourfunc))</langsyntaxhighlight>
 
* Obtaining the return value of a function
 
<syntaxhighlight lang ="bracmat">myfunc$!myarg:?myresult</langsyntaxhighlight>
 
Notice that the returned value can be any evaluated expression.
Line 639 ⟶ 957:
You can ignore the return value of a function <code>myfunc</code> as follows:
 
<syntaxhighlight lang ="bracmat">myfunc$!myarg&yourfunc$!yourarg</langsyntaxhighlight>
 
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
 
<langsyntaxhighlight lang="bracmat">`(myfunc$!myarg)&yourfunc$!yourarg</langsyntaxhighlight>
 
* Stating whether arguments are passed by value or by reference
Line 653 ⟶ 971:
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.
 
<langsyntaxhighlight lang="bracmat">( ( plus
= a b
. !arg:%?a ?b
Line 662 ⟶ 980:
& out$("1+2, not partial:" plus$(1 2))
& out$("1+2, partial:" (plus$1)$2)
);</langsyntaxhighlight>
 
Output:
Line 668 ⟶ 986:
<pre>1+2, not partial: 3
1+2, partial: 3</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">/* function with no argument */
f();
 
Line 734 ⟶ 1,051:
 
/* Scalar values are passed by value by default. However, arrays are passed by reference. */
/* Pointers *sort of* work like references, though. */</langsyntaxhighlight>
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="c sharp">
=={{header|C Sharp}}==
<lang c sharp>
/* a function that has no argument */
public int MyFunction();
Line 768 ⟶ 1,084:
public internal MyFunction();
int returnValue = MyFunction();
</syntaxhighlight>
</lang>
=={{header|C++}}==
<syntaxhighlight lang="c++">
<lang C++>
 
/* function with no arguments */
foo();
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="c++">
<lang C++>
/* passing arguments by value*/
/* function with one argument */
Line 782 ⟶ 1,098:
/* function with multiple arguments */
baz(arg1, arg2);
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="c++">
<lang C++>
/* get return value of a function */
variable = function(args);
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="c++">
<lang C++>
#include <iostream>
using namespace std;
Line 804 ⟶ 1,120:
cout<<"x = "<<x<<endl; /* should produce result "x = 1" */
}
</syntaxhighlight>
</lang>
=={{header|Clojure}}==
Note: I ran all these examples in the REPL so there is no printed output; instead I have denoted the value of each expression evaluated using `;=>'.
 
'''Calling a function that requires no arguments'''
<syntaxhighlight lang="clojure">
(defn one []
"Function that takes no arguments and returns 1"
1)
 
(one); => 1
</syntaxhighlight>
'''Calling a function with a fixed number of arguments'''
<syntaxhighlight lang="clojure">
(defn total-cost [item-price num-items]
"Returns the total price to buy the given number of items"
(* item-price num-items))
 
(total-cost 1 5); => 5
</syntaxhighlight>
'''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)
<syntaxhighlight lang="clojure">
(defn total-cost-with-discount [item-price num-items & [discount-percentage]]
"Returns total price to buy the items after discount is applied (if given)"
(let [discount (or discount-percentage 0)] ;; Assign discount to either the discount-percentage (if given) or default 0 if not
(-> item-price
(* num-items) ;; Calculate total cost
(* (- 100 discount)) ;; Apply discount
(/ 100.0))))
 
;; Now we can use the function without the optional arguments, and see the same behaviour as our total-cost function
(total-cost-with-discount 1 5); => 5
 
;; Or we can add the third parameter to calculate the cost with 20% discount
(total-cost-with-discount 1 5 20); => 4
</syntaxhighlight>
'''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.
 
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
([city place-name] (str place-name ", " city))
([city street house-number] (str house-number " " street ", " city))
([city street house-number apartment] (str house-number " " street ", Apt. " apartment ", " city)))
 
;; To call the function you just need to pass whatever arguments you are supplying as you would with a fixed number
 
;; First case- the queen doesn't need a street name
(make-address "London" "Buckingham Palace"); => "Buckingham Palace, London"
 
;; Second case
(make-address "London" "Downing Street" 10); => "10 Downing Street, London"
 
;; Third case
(make-address "London" "Baker Street" 221 "B"); => "221 Baker Street, Apt. B, London"
</syntaxhighlight>
'''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.
<syntaxhighlight lang="clojure">
(defn make-mailing-label [{:keys [name address country]}]
"Returns the correct text to mail a letter to the addressee"
(str name "\n" address "\n" (or country "UK"))) ;; If country is nil, assume it is the UK
 
;; We can call it with all three arguments in a map to get mickey's international address
(make-mailing-label {:name "Mickey Mouse"
:address "1 Disney Avenue, Los Angeles"
:country "USA"}); => "Mickey Mouse\n1 Disney Avenue, Los Angeles\nUSA"
 
;; Or we can call it with fewer arguments for domestic mail
(make-mailing-label {:name "Her Majesty"
:address "Buckingham Palace, London"}); => "Her Majesty\nBuckingham Palace, London\nUK"
</syntaxhighlight>
'''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
<syntaxhighlight lang="clojure">
(defn multiply-by-10 [number]
(* 10 number))
 
(def fifty (multiply-by-10 5))
 
fifty; => 50
</syntaxhighlight>
 
'''Using a function in first-class context within an expression'''
 
Functions are always first-class, here are some examples of how they can be used in first class context:
 
You can use one function to create another
<syntaxhighlight lang="clojure">
(defn make-discount-function [discount-percent]
"Returns a function that takes a price and applies the given discount"
(fn [price] (-> price
(* (- 100 discount-percent))
(/ 100.0))))
 
;; Now we can create a '20% off' function to calculate prices with your discount card
(def discount-20pc (make-discount-function 20))
 
;; Use the function to calculate some discount prices
(discount-20pc 100); => 80
(discount-20pc 5); => 4
 
;; Your friend has a better discount card, we can use the same function to create their discount card function
(def discount-50pc (make-discount-function 50))
(discount-50pc 100); => 50
(discount-50pc 5); => 2.5
</syntaxhighlight>
 
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
;; We can store their discount functions in a map
 
(def discount-cards {"Anna" discount-20pc
"Bill" discount-50pc
"Charlie" identity}) ;; Identity returns whatever value was passed to the function (in this case it will be price)
 
;; Now we can access them by cardholder name in another function
(defn calculate-discounted-price [price shopper-name]
"Applies the correct discount for the person"
(let [discount-fn (get discount-cards shopper-name)] ;; Get the right discount function
(discount-fn price))) ;; Apply discount function to the price
 
(calculate-discounted-price 100 "Anna"); => 80
(calculate-discounted-price 100 "Bill"); => 50
(calculate-discounted-price 100 "Charlie"); => 100
</syntaxhighlight>
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]
(str "£" price))
 
(defn format-price-us [price]
(str "$" price))
 
;; And one function that takes a price formatting function as an argument
 
(defn format-receipt [item-name price price-formatting-function]
"Return the item name and price formatted according to the function"
(str item-name
" "
(price-formatting-function price))) ;; Call the format function to get the right representation of the price
 
(format-receipt "Loo Roll" 5 format-price-uk); => "Loo Roll £5"
 
(format-receipt "Toilet Paper" 5 format-price-us); => "Toilet Paper $5"
</syntaxhighlight>
'''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))
 
;; Then the variable holds the value
receipt-us; => "Toilet Paper $5"
 
;; Or you can use it in a call to another function
 
(defn add-store-name [receipt]
"A function to add a footer to the receipt"
(str receipt "\n Thanks for shopping at Safeway" ))
 
;; 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"
</syntaxhighlight>
'''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
 
(+ 5 5); => 10
 
;; Using custom defined addition
 
(defn ? [a b]
"Returns the sum of two numbers"
(+ a b))
 
(? 5 5); => 10
 
;; Overriding a built in function is possible but not recommended
 
(defn * [a b] ;; Redefining the multiplication operator
"Returns the sum of two numbers"
(+ a b))
 
(* 5 5); => 10
</syntaxhighlight>
'''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
 
(defn no-return-value [a]
(print (str "Your argument was" a "; now returning nil")))
 
(no-return-value "hi"); => nil
</syntaxhighlight>
'''Stating whether arguments are passed by value or by reference'''
All data structures are immutable, so they are passed by value only.
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"
:title "Your Majesty"
:address "Buckingham Palace"
:pets ["Corgi" "Horse"]})
 
;; A function to modify the data
(defn adopt-pet [person pet]
"Adds pet to the person's list of pets"
(update person
:pets
#(conj % pet)))
 
;; Calling the function returns a new data structure with the modified pets
(adopt-pet the-queen "Ferret"); => {:name "Elizabeth":title "Your Majesty" :address "Buckingham Palace" :pets ["Corgi" "Horse" "Ferret]}
 
;; The original data structure is not changed
the-queen; => {:name "Elizabeth" :title "Your Majesty" :address "Buckingham Palace" :pets ["Corgi" "Horse"]}</syntaxhighlight>
 
'''Is partial application possible and how'''
 
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"
(-> price
(* (- 100 discount-percentage)) ;; Apply discount
(/ 100.0)))
 
;; Here we have assigned the variable to a partial function
;; It means 'call apply-discount with 10 as the first argument'
(def discount-10pc-option-1 (partial apply-discount 10))
 
;; And is equivalent to this:
(defn discount-10pc-option-2 [price]
(apply-discount 10 price))
 
(discount-10pc-option-1 100); => 90
 
(discount-10pc-option-2 100); => 90
</syntaxhighlight>
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol">CALL "No-Arguments"
 
*> Fixed number of arguments.
Line 871 ⟶ 1,428:
ACCEPT Foo *> Get a PROGRAM-ID from the user.
CALL "Use-Func" USING Foo
CALL Foo USING Bar</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# Calling a function that requires no arguments
foo()
Line 927 ⟶ 1,483:
 
add2 1 #=> 3
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
;Calling a function that requires no arguments
(defun a () "This is the 'A' function")
Line 956 ⟶ 1,511:
(apply function (append args-1 args-2))))
(funcall (curry #'+ 1) 2)
</syntaxhighlight>
</lang>
=={{header|Cubescript}}==
<syntaxhighlight lang="cubescript">
// No arguments
myfunction
 
// All functions can take a variable number of arguments.
// These can be accessed from within the function with the aliases:
// $arg1, $arg2, $arg3... $numargs tells the amount of args passed.
myfunction word "text string" 1 3.14
 
// Getting a function's return value
retval = (myfunction)
 
// Trying to do a variable lookup on a builtin function will return an empty
// string. This can be used to distinguish builtin functions from user-defined
// ones.
if (strcmp $echo "") [echo builtin function] // true
if (strcmp $myfunction "") [echo builtin function] // false
</syntaxhighlight>
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.traits;
 
enum isSubroutine(alias F) = is(ReturnType!F == void);
Line 1,061 ⟶ 1,634:
alias foo6b = partial!(foo6, 5);
assert(foo6b(6) == 11);
}</langsyntaxhighlight>
{{out}}
<pre>true
false</pre>
=={{header|Dart}}==
<syntaxhighlight lang="dart">void main() {
// Function definition
// See the "Function definition" task for more info
void noArgs() {}
void fixedArgs(int arg1, int arg2) {}
void optionalArgs([int arg1 = 1]) {}
void namedArgs({required int arg1}) {}
int returnsValue() {return 1;}
// Calling a function that requires no arguments
noArgs();
// Calling a function with a fixed number of arguments
fixedArgs(1, 2);
// Calling a function with optional arguments
optionalArgs();
optionalArgs(2);
// Calling a function with named arguments
namedArgs(arg1: 1);
// Using a function in statement context
if (true) {
noArgs();
}
// Obtaining the return value of a function
var value = returnsValue();
}</syntaxhighlight>
=={{header|Delphi}}==
Delphi allows everything what [[#Pascal|Pascal]] allows.
In addition, the following is ''also'' possible:
 
Calling a function without arguments and obtaining its return value:
<syntaxhighlight lang="delphi">foo()</syntaxhighlight>
Calling a function with optional arguments:
<syntaxhighlight lang="delphi">foo(1)</syntaxhighlight>
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:
<syntaxhighlight lang="delphi">writeLn('Hello world.');
foo;
writeLn('Goodbye world')</syntaxhighlight>
Like above, an empty parameter list, i. e. <tt>()</tt>, could be supplied too.
=={{header|Dragon}}==
 
* Calling a function that requires no arguments
<syntaxhighlight lang="dragon">myMethod()</syntaxhighlight>
 
* Calling a function with a fixed number of arguments
<syntaxhighlight lang="dragon">myMethod(97, 3.14)</syntaxhighlight>
=={{header|Dyalect}}==
 
Calling a function that requires no arguments:
 
<syntaxhighlight lang="dyalect">func foo() { }
foo()</syntaxhighlight>
 
Calling a function with a fixed number of arguments:
 
<syntaxhighlight lang="dyalect">func foo(x, y, z) { }
foo(1, 2, 3)</syntaxhighlight>
 
Calling a function with optional arguments:
 
<syntaxhighlight lang="dyalect">func foo(x, y = 0, z = 1) { }
foo(1)</syntaxhighlight>
 
Calling a function with a variable number of arguments:
 
<syntaxhighlight lang="dyalect">func foo(args...) { }
foo(1, 2, 3)</syntaxhighlight>
 
Calling a function with named arguments:
 
<syntaxhighlight lang="dyalect">func foo(x, y, z) { }
foo(z: 3, x: 1, y: 2)</syntaxhighlight>
 
Using a function in statement context:
 
<syntaxhighlight lang="dyalect">func foo() { }
if true {
foo()
}</syntaxhighlight>
 
Using a function in first-class context within an expression:
 
<syntaxhighlight lang="dyalect">func foo() { }
var x = if foo() {
1
} else {
2
}</syntaxhighlight>
 
Obtaining the return value of a function:
 
<syntaxhighlight lang="dyalect">func foo(x) { x * 2 }
var x = 2
var y = foo(x)</syntaxhighlight>
 
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
 
//You can however write a function that would check if a given function is declared in "lang" module:
func isBuiltin(fn) =>
fn.Name is not nil && fn.Name in lang && lang[fn.Name] == fn
 
//Usage:
func foo() { } //A user-defined function
print(isBuiltin(foo)) //Prints: false
print(isBuiltin(assert)) //Prints: true</syntaxhighlight>
 
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 bar(x) { return x * 2 } //explicitly returns value (keyword "return" can be omitted)</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="dyalect">//Using a closure:
func apply(fun, fst) { snd => fun(fst, snd) }
 
//Usage:
func sum(x, y) { x + y }
 
var sum2 = apply(sum, 2)
var x = sum2(3) //x is 5
 
//By second argument
func flip(fun) { (y, x) => fun(x, y) }
func sub(x, y) { x - y }
 
var sub3 = apply(flip(sub), 3)
x = sub3(9) //x is 6</syntaxhighlight>
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu"># all functions used are from the standard library
# calling a function with no arguments:
random-int
Line 1,098 ⟶ 1,813:
# partial application is not possible, due to the fact that
# a function's arity is a property of its behavior and not
# of its definition</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func sqr n .
return n * n
.
print sqr 3
#
proc divmod a b . q r .
q = a div b
r = a mod b
.
divmod 11 3 q r
print q & " " & r
#
subr sqr2
a = a * a
.
a = 5
sqr2
print a
</syntaxhighlight>
 
=={{header|Ecstasy}}==
<b><i>Calling a function that requires no arguments:</i></b>
<syntaxhighlight lang="java">
foo(); // <-- this is "invoking a function in statement context"
Int x = bar(); // <-- this is "invoking a function in expression context"
</syntaxhighlight>
 
<b><i>Calling a function with a fixed number of arguments:</i></b>
<syntaxhighlight lang="java">
foo(1, 2, 3);
Int x = bar(4, 5, 6);
</syntaxhighlight>
 
<b><i>Calling a function with optional arguments:</i></b>
<syntaxhighlight lang="java">
module CallOptArgsFunc {
static Int foo(Int a=0, Int b=99, Int c=-1) {
return a + b + c;
}
 
void run() {
@Inject Console console;
console.print($"{foo()=}");
console.print($"{foo(1)=}");
console.print($"{foo(1, 2)=}");
console.print($"{foo(1, 2, 3)=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
foo()=98
foo(1)=99
foo(1, 2)=2
foo(1, 2, 3)=6
</pre>
 
<b><i>Calling a function with a variable number of arguments:</i></b>
<syntaxhighlight lang="java">
module CallVarArgsFunc {
// Ecstasy does not have a var-args concept; instead, array notation is used
static Int foo(Int[] args = []) {
return args.size;
}
 
void run() {
@Inject Console console;
console.print($"{foo()=}");
console.print($"{foo([])=}");
console.print($"{foo([1])=}");
console.print($"{foo([1, 2])=}");
console.print($"{foo([1, 2, 3])=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
foo()=0
foo([])=0
foo([1])=1
foo([1, 2])=2
foo([1, 2, 3])=3
</pre>
 
<b><i>Calling a function with named arguments:</i></b>
<syntaxhighlight lang="java">
module CallNamedArgsFunc {
static String foo(Int a=1, Int b=2, Int c=3) {
return $"a:{a}, b:{b}, c:{c}";
}
 
void run() {
@Inject Console console;
console.print($"{foo(c=9, b=8, a=7)=}");
console.print($"{foo(4, c=6, b=5)=}");
console.print($"{foo(c=99)=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
foo(c=9, b=8, a=7)=a:7, b:8, c:9
foo(4, c=6, b=5)=a:4, b:5, c:6
foo(c=99)=a:1, b:2, c:99
</pre>
 
<b><i>Using a function in first-class context within an expression:</i></b> Functions are always first class in Ecstasy; everything (including classes, types, methods, properties, functions, variables, etc.) is an object.
<syntaxhighlight lang="java">
module FirstClassFunctions {
@Inject Console console;
void run() {
function Int(String) stringLen = s -> s.size;
function Int(Int, Int) sum = (n1, n2) -> n1+n2;
String[] testData = ["abc", "easy", "as", "123"];
console.print($|total string length of values in {testData} =\
| {testData.map(stringLen).reduce(0, sum)}
);
}
}
</syntaxhighlight>
 
{{out}}
<pre>
total string length of values in [abc, easy, as, 123] = 12
</pre>
 
<b><i>Obtaining the return value of a function:</i></b>
<syntaxhighlight lang="java">
module ObtainReturnValues {
(Int, String, Dec) foo() {
return 3, "hello!", 9.87;
}
 
void run() {
foo(); // ignore return values
Int i1 = foo(); // only use first returned value
(Int i2, String s2) = foo(); // only use first two returned values
(Int i3, String s3, Dec d3) = foo(); // use all returned values
Tuple<Int, String, Dec> t = foo(); // alternatively, get the tuple instead
 
@Inject Console console;
console.print($"{i3=}, {s3=}, {d3=}, {t=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
i3=3, s3=hello!, d3=9.87, t=(3, hello!, 9.87)
</pre>
 
<b><i>Distinguishing built-in functions and user-defined functions:</i></b>
<syntaxhighlight lang="java">
// Ecstasy does not have any built-in functions. However, there are two keywords
// ("is" and "as") that use a function-like syntax:
module IsAndAs {
Int|String foo() {
return "hello";
}
 
void run() {
@Inject Console console;
Object o = foo();
if (o.is(String)) { // <- looks like a function call
String s = o.as(String); // <- looks like a function call
console.print($"foo returned the string: {s.quoted()}");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
foo returned the string: "hello"
</pre>
 
<b><i>Distinguishing subroutines and functions:</i></b> There is no such thing as a subroutine in Ecstasy. There are only methods (virtual functions with a "this"), functions, and object constructors.
 
<b><i>Stating whether arguments are passed by value or by reference:</i></b> Ecstasy does not specify whether arguments are passed by value or by reference. However, since all Ecstasy types are <i>conceptually</i> reference types, the behavior is defined as if all arguments are references passed by value; this is the same model used by Java for all of its reference types.
 
<b><i>Is partial application possible and how:</i></b>
<syntaxhighlight lang="java">
module PartialApplication {
void foo(String s, Int i, Dec d) {
@Inject Console console;
console.print($"inside call to foo({s=}, {i=}, {d=})");
}
 
void run() {
// note that the "&" obtains the reference to the function, and suppresses the
// invocation thereof, so it is *allowed* in all three of these cases, but it
// is *required* in the third case:
function void(String, Int, Dec) unbound = foo; // or "foo(_, _, _)"
function void(String, Dec) partBound = unbound(_, 99, _);
function void() allBound = &partBound("world", 3.14);
 
unbound("nothing", 0, 0.0);
partBound("hello", 2.718);
allBound();
}
}
</syntaxhighlight>
 
{{out}}
<pre>
inside call to foo(s=nothing, i=0, d=0)
inside call to foo(s=hello, i=99, d=2.718)
inside call to foo(s=world, i=99, d=3.14)
</pre>
 
=={{header|Elena}}==
ELENA 4.x1:
Declaring closures
<langsyntaxhighlight lang="elena">
var c0 := (){ console.writeLine("No argument provided") };
var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") };
</syntaxhighlight>
</lang>
Calling a closure without arguments
<langsyntaxhighlight lang="elena">
c0();
</syntaxhighlight>
</lang>
Calling a closure with arguments
<langsyntaxhighlight lang="elena">
c2(2,4);
</syntaxhighlight>
</lang>
Passing arguments by reference:
<langsyntaxhighlight lang="elena">
var exch := (ref object x){ x := 2 };
var a := 1;
exch(ref a);
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
 
<langsyntaxhighlight lang="elixir">
# Anonymous function
 
Line 1,181 ⟶ 2,111:
end
end
</syntaxhighlight>
</lang>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun task = void by text about, fun code
writeLine(0U00b7 + " " + about)
code()
end
fun answer = void by var message do writeLine(" " + message) end
# few definitions
fun noArgumentsFunction = int by block do return 97 end
fun fixedArgumentsFunction = void by var a, var b do end
fun variadicFunction = void by text a, some var values do end
fun funArgumentFunction = var by fun f, var b do return f() + b end
task("Calling a function that requires no arguments", void by block
answer("Is supported.")
noArgumentsFunction()
end)
task("Calling a function with a fixed number of arguments", void by block
answer("Is supported.")
fixedArgumentsFunction(97, 3.14)
end)
task("Calling a function with optional arguments", void by block
answer("Not supported in EMal.")
end)
task("Calling a function with a variable number of arguments", void by block
answer("Variadic functions are supported.")
variadicFunction("mandatory", 97, 3.14)
variadicFunction("mandatory", 97)
end)
task("Calling a function with named arguments", void by block
answer("Not supported in EMal.")
end)
task("Using a function in statement context", void by block
answer("Is supported.")
if true do noArgumentsFunction()
else do fixedArgumentsFunction(97, 3.14) end
end)
task("Using a function in first-class context within an expression", void by block
answer("Functions are first class, can be passed as arguments and returned.")
answer(funArgumentFunction(noArgumentsFunction, 3.14))
end)
task("Obtaining the return value of a function", void by block
answer("Is supported.")
int value = noArgumentsFunction()
answer(value)
end)
task("Distinguishing built-in functions and user-defined functions", void by block
answer("No distinction.")
end)
task("Distinguishing subroutines and functions", void by block
answer("No distinction, we support void return type.")
end)
task("Stating whether arguments are passed by value or by reference", void by block
answer("Pass by value, but text, blob, objects hold a reference.")
end)
task("Is partial application possible and how", void by block
answer("Is supported.")
^|I had some confusion about partial application and currying, thanks to these links:
| https://stackoverflow.com/questions/218025/what-is-the-difference-between-currying-and-partial-application
| https://web.archive.org/web/20161023205431/http://www.uncarved.com/articles/not_curryin
|^
# Partial applying
fun add = int by int a, int b do return a + b end
fun partial = fun by fun f, int a
return int by int b
return add(a, b)
end
end
fun add7 = partial(add, 7)
answer(add(7, 5))
answer(add7(5))
# Currying
fun addN = fun by int n
return int by int x
return x + n
end
end
fun plus = int by int a, int b
fun addA = addN(a)
return addA(b)
end
answer(plus(7, 5))
end)
</syntaxhighlight>
{{out}}
<pre>
· Calling a function that requires no arguments
Is supported.
· Calling a function with a fixed number of arguments
Is supported.
· Calling a function with optional arguments
Not supported in EMal.
· Calling a function with a variable number of arguments
Variadic functions are supported.
· Calling a function with named arguments
Not supported in EMal.
· Using a function in statement context
Is supported.
· Using a function in first-class context within an expression
Functions are first class, can be passed as arguments and returned.
100.14
· Obtaining the return value of a function
Is supported.
97
· Distinguishing built-in functions and user-defined functions
No distinction.
· Distinguishing subroutines and functions
No distinction, we support void return type.
· Stating whether arguments are passed by value or by reference
Pass by value, but text, blob, objects hold a reference.
· Is partial application possible and how
Is supported.
12
12
12
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
no_argument()
one_argument( Arg )
Line 1,197 ⟶ 2,243:
% 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)
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">// No arguments
noArgs()
 
Line 1,242 ⟶ 2,287:
 
// Partial application example
let add2 = (+) 2</langsyntaxhighlight>
 
=={{header|Factor}}==
* Calling a word with no arguments:
<syntaxhighlight lang Factor="factor">foo</langsyntaxhighlight>
 
* 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.
<syntaxhighlight lang Factor="factor">foo</langsyntaxhighlight>
 
* 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:
<langsyntaxhighlight Factorlang="factor">"a" "b" "c" 3 narray
! { "a" "b" "c" }</langsyntaxhighlight>
 
* The named arguments idiom is to define a tuple, set its slots, and pass it to a word:
<langsyntaxhighlight Factorlang="factor"><email>
"jack@aol.com" >>from
{ "jill@aol.com" } >>to
"Hello there" >>subject
body >>body
send-email</langsyntaxhighlight>
 
* First-class context: this pushes a word to the stack. Use execute to evaluate.
<syntaxhighlight lang Factor="factor">\ foo</langsyntaxhighlight>
Additionally, you can put words directly inside sequences and quotations for deferred execution:
<syntaxhighlight lang Factor="factor">{ foo } [ foo ]</langsyntaxhighlight>
 
* Obtaining the return value, which will be placed on the stack:
<syntaxhighlight lang Factor="factor">foo</langsyntaxhighlight>
 
* 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.
<syntaxhighlight lang Factor="factor">\ foo primitive?</langsyntaxhighlight>
 
* Factor makes no distinction between subroutines and functions.
 
* It's not perfectly accurate to think of words as passing arguments by reference (or at all), since all words simply operate on the data stack. However, it is still important for the programmer to understand that words which make duplicates of objects such as <tt>dup</tt> and <tt>over</tt> do so by creatingcopying references. If one wishes for a uniqueshallow copy of a non-immediate object, one may use <tt>clone</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>:
<langsyntaxhighlight Factorlang="factor">{ 1 2 3 } 2 [ - ] curry map .
! { -1 0 1 }</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">a-function \ requiring no arguments
a-function \ with a fixed number of arguents
a-function \ having optional arguments
Line 1,309 ⟶ 2,352:
: up ( n -- ) negate down ;
: right ( n -- ) 0 move ;
: left ( n -- ) negate right ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
===Examples===
<langsyntaxhighlight Fortranlang="fortran">program main
implicit none
integer :: a
Line 1,383 ⟶ 2,425:
write(*,*) 'Output of subroutine: ', a
end subroutine
</syntaxhighlight>
</lang>
 
<pre>
Line 1,416 ⟶ 2,458:
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 <langsyntaxhighlight Fortranlang="fortran"> REAL this,that
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.</langsyntaxhighlight>
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.
 
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 <langsyntaxhighlight Fortranlang="fortran"> H = A + B
IF (blah) H = 3*H - 7</langsyntaxhighlight>
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.
 
Fortran also offers the ability to pass a function as a parameter such that the recipient routine can call it, as in <langsyntaxhighlight Fortranlang="fortran"> REAL FUNCTION INTG8(F,A,B,DX) !Integrate function F.
EXTERNAL F !Some function of one parameter.
REAL A,B !Bounds.
Line 1,454 ⟶ 2,496:
WRITE (6,*) "Result=",INTG8(SIN, 0.0,8*ATAN(1.0),0.01)
WRITE (6,*) "Linear=",INTG8(TRIAL,0.0,1.0, 0.01)
END</langsyntaxhighlight>
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.
 
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 <langsyntaxhighlight Fortranlang="fortran"> TYPE MIXED
CHARACTER*12 NAME
INTEGER STUFF
END TYPE MIXED
TYPE(MIXED) LOTS(12000)</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="fortress">
component call_a_function
export Executable
Line 1,506 ⟶ 2,547:
end
end
</syntaxhighlight>
</lang>
=={{header|Free Pascal}}==
See [[#Delphi|Delphi]].
Note, calling a <tt>function</tt> as if it was a <tt>procedure</tt> [i. e. ''discarding'' the return value] is only permitted if you set the compiler setting <tt>{$extendedSyntax on}</tt>/<tt>{$X+}</tt>.
This is the default.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
Sub Saludo()
Print "Hola mundo!"
End Sub
 
Function Copialo(txt As String, siNo As Short, final As String = "") As String
Dim nuevaCadena As String
For cont As Short = 1 To siNo
nuevaCadena &= txt
Next
Return Trim(nuevaCadena) & final
End Function
 
Sub testNumeros(a As Integer, b As Integer, c As Integer = 0)
Print a, b, c
End Sub
 
Sub testCadenas(txt As String)
For cont As Byte = 0 To Len(txt)
Print Chr(txt[cont]); "";
Next cont
End Sub
 
Saludo
Print Copialo("Saludos ", 6)
Print Copialo("Saludos ", 3, "!!")
?
testNumeros(1, 2, 3)
testNumeros(1, 2)
?
testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")
</syntaxhighlight>
{{out}}
<pre>Hola mundo!
Saludos Saludos Saludos Saludos Saludos Saludos
Saludos Saludos Saludos!!
 
1 2 3
1 2 0
 
1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'</pre>
 
=={{header|FutureBasic}}==
No arguments
<syntaxhighlight lang="futurebasic">
void local fn MyFunction
print @"MyFunction"
end fn
 
fn MyFunction
 
HandleEvents
</syntaxhighlight>
 
Fixed arguments - args passed by value
<syntaxhighlight lang="futurebasic">
void local fn MyFunction( arg1 as long, arg2 as long, arg3 as long )
print @"MyFunction"
end fn
 
fn MyFunction( 1, 2, 3 )
 
HandleEvents
</syntaxhighlight>
 
Variable arguments - args passed by value
<syntaxhighlight lang="futurebasic">
void local fn MyFunction( count as long, ... )
va_list ap
long i, value
va_start( ap, count )
for i = 1 to count
value = fn va_arglong( ap )
print value
next
va_end( ap )
end fn
 
fn MyFunction( 3, 12, 24, 36 )
 
HandleEvents
</syntaxhighlight>
 
Return value - arg passed by value
<syntaxhighlight lang="futurebasic">
local fn MultiplyByThree( value as long ) as long
end fn = value * 3
 
print fn MultiplyByThree( 13 )
 
HandleEvents
</syntaxhighlight>
 
Argument passed by reference
<syntaxhighlight lang="futurebasic">
void local fn MultiplyByThree( value as ^long )
*value *= 3
end fn
 
long num
num = 9
fn MultiplyByThree( @num )
print num
 
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=1bbbeb240f6fbca4b893271f1a19833b Click this link to run this code]'''<br>
Some of the uses of Procedures/Functions in Gambas
<langsyntaxhighlight lang="gambas">Public Sub Main()
 
Hello
Line 1,535 ⟶ 2,692:
Print "Hello world!"
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,542 ⟶ 2,699:
Hello Hello Hello!!
</pre>
 
 
 
=={{header|Go}}==
The following examples use functions from the standard packages
plus a few dummy local functions:
::<langsyntaxhighlight lang="go">import (
"image"
"image/gif"
Line 1,556 ⟶ 2,715:
func f() (int, float64) { return 0, 0 }
func g(int, float64) int { return 0 }
func h(string, ...int) {}</langsyntaxhighlight>
* Calling with no arguments and calling with a fixed number of arguments:
::<langsyntaxhighlight lang="go"> f()
g(1, 2.0)
// If f() is defined to return exactly the number and type of
Line 1,566 ⟶ 2,725:
//h("fail", f())
// But this will:
g(g(1, 2.0), 3.0)</langsyntaxhighlight>
* 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). <langsyntaxhighlight lang="go"> h("ex1")
h("ex2", 1, 2)
h("ex3", 1, 2, 3, 4)
Line 1,575 ⟶ 2,734:
h("ex4", list...)
// but again, not mixed with other arguments, this won't compile:
//h("fail", 2, list...)</langsyntaxhighlight>
* 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>). <langsyntaxhighlight lang="go"> gif.Encode(ioutil.Discard, image.Black, &gif.Options{NumColors: 16})</langsyntaxhighlight>
* Optional arguments are supported.
::<syntaxhighlight lang="go">package main
 
import "fmt"
 
type Params struct {
a, b, c int
}
func doIt(p Params) int {
return p.a + p.b + p.c
}
 
func main() {
fmt.Println(doIt(Params{a: 1, c: 9})) // prt 10
}</syntaxhighlight>
* Named arguments are supported.
::<syntaxhighlight lang="go">package main
 
import "fmt"
 
func bar(a, b, c int) {
fmt.Printf("%d, %d, %d", a, b, c)
}
 
func main() {
args := make(map[string]int)
args["a"] = 3
args["b"] = 2
args["c"] = 1
bar(args["a"], args["b"], args["c"]) // prt 3, 2, 1
}</syntaxhighlight>
 
* Within a statement context.
::Assignment statements are shown later. Only functions returning a single value can be used in a single value context: <langsyntaxhighlight lang="go"> if 2*g(1, 3.0)+4 > 0 {}</langsyntaxhighlight>
* In a first-class context:
::<langsyntaxhighlight lang="go"> fn := func(r rune) rune {
if unicode.IsSpace(r) {
return -1
Line 1,589 ⟶ 2,780:
strings.Map(fn, "Spaces removed")
strings.Map(unicode.ToLower, "Test")
strings.Map(func(r rune) rune { return r + 1 }, "shift")</langsyntaxhighlight>
* Obtaining the value:
::<syntaxhighlight lang="text"> a, b := f() // multivalue return
_, c := f() // only some of a multivalue return
d := g(a, c) // single return value
e, i := g(d, b), g(d, 2) // multiple assignment</langsyntaxhighlight>
* 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). <langsyntaxhighlight lang="go"> list = append(list, a, d, e, i)
i = len(list)</langsyntaxhighlight>
* Go has no subroutines, just functions and methods.
* 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).
* Go arguments are passed by value or by reference
* Partial application is not directly supported.
::<syntaxhighlight lang="go">package main
 
import "fmt"
 
// int parameter, so arguments will be passed to it by value.
func zeroval(ival int) {
ival = 0
}
// has an *int parameter, meaning that it takes an int pointer.
func zeroptr(iptr *int) {
*iptr = 0
}
func main() {
i := 1
fmt.Println("initial:", i) // prt initial: 1
zeroval(i)
fmt.Println("zeroval:", i) // prt zeroval: 1
zeroptr(&i)
fmt.Println("zeroptr:", i) // prt zeroptr: 0
fmt.Println("pointer:", &i) // prt pointer: 0xc0000140b8
}</syntaxhighlight>
* Partial and Currying is not directly supported.
::However something similar can be done, see [[Partial function application#Go]]
::<syntaxhighlight lang="go">package main
 
import "fmt"
 
func mkAdd(a int) func(int) int {
return func(b int) int {
return a + b
}
}
func sum(x, y int) int {
return x + y
}
 
func partialSum(x int) func(int) int {
return func(y int) int {
return sum(x, y)
}
}
func main() {
// Is partial application possible and how
add2 := mkAdd(2)
add3 := mkAdd(3)
fmt.Println(add2(5), add3(6)) // prt 7 9
// Currying functions in go
partial := partialSum(13)
fmt.Println(partial(5)) //prt 18
}</syntaxhighlight>
 
 
=={{header|Groovy}}==
There are two types of first-class functions in Groovy.
 
# The first are functions defined in scripts, although they behave as if they are methods of the script "class".
# The second are closures, which are similar to lambdas in Java, except that they are defined as their own class type and must be explicitly converted to single-method "functional" interfaces. There are many methods within the Groovy API that accept closures as arguments.
 
 
* Calling a function that requires no arguments
<syntaxhighlight lang="groovy">noArgs()</syntaxhighlight>
 
* 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
<syntaxhighlight lang="groovy">optArgs("It's", "a", "beautiful", "day")
optArgs("It's", "a", "beautiful")
optArgs("It's", "a")
optArgs("It's")</syntaxhighlight>
 
* 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")
varArgs("It's")</syntaxhighlight>
 
* Calling a function with named arguments
It's complicated
 
* 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
** Create new functions from preexisting functions at run-time
<syntaxhighlight lang="groovy">def oldFunc = { arg1, arg2 -> arg1 + arg2 }
def newFunc = oldFunc.curry(30)
assert newFunc(12) == 42</syntaxhighlight>
** Store functions in collections
<syntaxhighlight lang="groovy">def funcList = [func1, func2, func3]</syntaxhighlight>
** Use functions as arguments to other functions
<syntaxhighlight lang="groovy">def eltChangeFunc = { it * 3 - 1 }
def changedList = list.collect(eltChangeFunc)</syntaxhighlight>
** 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() }
: { String transString -> (transString + s) * reps }
}
def func = funcMaker("a", 2, true)
assert func("pook") == "POOKAPOOKA"</syntaxhighlight>
 
* 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
There are no "built-in" functions. All is illusion.
 
* Stating whether arguments are passed by value or by reference
As with Java everything is passed by value, but object values are actually references (pointers). So,
** if the argument is a primative it is passed by value and changes are not manifested in the caller's context.
** if the argument is an object reference, the reference is passed by value and changes to the reference (re-assignment, for example) are not manifested in the caller's context, but changes in the object are.
 
 
* Is partial application possible and how
Partial application in Groovy is performed via currying (demonstrated above)
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">
-- Calling a function with a fixed number of arguments
multiply x y = x * y
Line 1,635 ⟶ 2,939:
-- Distinguishing subroutines and functions
-- Stating whether arguments are passed by value or by reference
</syntaxhighlight>
</lang>
 
=={{header|i}}==
<langsyntaxhighlight 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.
 
Line 1,666 ⟶ 2,969:
end
}
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon have generalized procedures and syntax that are used to implement functions, subroutines and generators.
Line 1,680 ⟶ 2,982:
For more information see [[Icon%2BUnicon/Intro|Icon and Unicon Introduction on Rosetta]]
 
<langsyntaxhighlight Iconlang="icon">procedure main() # demonstrate and describe function calling syntax and semantics
 
# normal procedure/function calling
Line 1,709 ⟶ 3,011:
f("x:=",1,"y:=",2) # named parameters (user defined)
end</langsyntaxhighlight>
 
=={{header|J}}==
 
Line 1,717 ⟶ 3,018:
A verb, in J, typically supports two syntactic variants:
 
<langsyntaxhighlight lang="j"> verb noun
noun verb noun</langsyntaxhighlight>
 
And a noun, in J, is an array.
Line 1,724 ⟶ 3,025:
An argument list can be represented by an array. Thus, when dealing with multiple arguments, a typical form is:
 
<syntaxhighlight lang ="j"> function argumentList</langsyntaxhighlight>
 
Here, <code>function</code> is a verb and <code>argumentList</code> is a noun.
Line 1,730 ⟶ 3,031:
For example:
 
<syntaxhighlight lang ="j"> sum(1,2,3)</langsyntaxhighlight>
 
Here <code>sum</code> is a verb and <code>(1,2,3)</code> is a noun.
Line 1,736 ⟶ 3,037:
Thus:
 
''A function that requires no arguments'' can be simulated by calling a function with empty argument list: <syntaxhighlight lang ="j">f''</langsyntaxhighlight> 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. <langsyntaxhighlight lang="j">f 'one argument'</langsyntaxhighlight>and <langsyntaxhighlight lang="j">'this example has two arguments' f 'the other argument'</langsyntaxhighlight> 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.
 
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: <langsyntaxhighlight lang="j"> f 1,2,3,4,5</langsyntaxhighlight> and here's a boxed example with five arguments: <langsyntaxhighlight lang="j">f (<1),(<2),(<3),(<4),(<5) </langsyntaxhighlight> Note that the last set of parenthesis is unnecessary <langsyntaxhighlight lang="j">f (<1),(<2),(<3),(<4),<5</langsyntaxhighlight> Note also that J offers some syntactic sugar for this kind of list <langsyntaxhighlight lang="j">f 1; 2; 3; 4; <5</langsyntaxhighlight>. 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). <langsyntaxhighlight lang="j">f 1; 2; 3; 4; 5</langsyntaxhighlight>
 
''A function with named arguments'' can be accomplished by calling a function with the names of the arguments. <langsyntaxhighlight lang="j">f 'george';'tom';'howard'</langsyntaxhighlight> 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: <langsyntaxhighlight lang="j">1 2 3 f 'george';'tom';'howard'</langsyntaxhighlight> 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:<langsyntaxhighlight lang="j"> obj=: conew'blank'
george__obj=: 1
tom__obj=: 2
howard__obj=: 3
f obj
coerase obj</langsyntaxhighlight> Name/value pairs can also be used for this purpose and can be implemented in various ways, including passing names followed by values <langsyntaxhighlight lang="j">f 'george';1;'tom';2;'howard';3</langsyntaxhighlight> and passing a structure of pairs <langsyntaxhighlight lang="j">f ('george';1),('tom';2),:(howard';3)</langsyntaxhighlight> Or, for example, the pairs could be individually boxed: <langsyntaxhighlight lang="j">f ('george';1);('tom';2);<howard';3</langsyntaxhighlight>
 
''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: <syntaxhighlight lang ="j">1 + f 2</langsyntaxhighlight>
 
The only ''differences that apply to calling builtin functions rather than user defined functions'' is spelling of the function names.
 
There are no ''differences between calling subroutines and functions'' because J defines neither <code>subroutines</code> nor <code>functions</code>. Instead, J defines <code>verbs</code>, <code>adverbs</code>, and <code>conjunctions</code> which for the purpose of this task are treated as functions. (All of the above examples used verbs. J's adverbs and conjunctions have stronger [[wp:Valence|valence]] than its verbs.)
 
=={{header|Java}}==
<kbd><i>"Calling a function that requires no arguments."</i></kbd><br/>
The parentheses are required.
<syntaxhighlight lang="java">
Object.methodName();
</syntaxhighlight>
<p>
<kbd><i>"Calling a function with a fixed number of arguments."</i></kbd>
<syntaxhighlight lang="java">
Object.methodName("rosetta", "code");
</syntaxhighlight>
</p>
<p>
<kbd><i>"Calling a function with optional arguments."</i></kbd><br/>
Java doesn't offer the ability to optionalize parameters, although there is something similar.<br/>
A <kbd>varargs</kbd>, or "Variable Arguments", parameter, could be of 0 length.<br/>
So if you're only parameter is a <kbd>vararg</kbd> parameter, it's possible to not supply any input.
This could be viewed, in some situations, as an optional parameter.
</p>
<p>
<kbd><i>"Calling a function with a variable amount of arguments."</i></kbd><br/>
There is no special syntax, you simply offer the arguments as required.
</p>
<p>
<kbd><i>"Calling a function with named arguments."</i></kbd><br/>
Java does not offer this feature.
</p>
<p>
<kbd><i>"Using a function in a statement context."</i></kbd><br/>
Java is not a functional programming language, although Java 8 added basic closures and lambda expressions.<br/>
They are not in anyway as robust as functional languages like JavaScript.<br/>
A lambda works specifically with an <code>interface</code> that requires only 1 abstraction.<br/>
Consider the following <kbd>interface</kbd>.
<syntaxhighlight lang="java">
interface Example {
int add(int valueA, int valueB);
}
</syntaxhighlight>
You could then implement this interface with a lambda, as opposed to creating an anonymous-class.<br/>
Consider the following method.
<syntaxhighlight lang="java">
int sum(Example example) {
return example.add(1, 2);
}
</syntaxhighlight>
You would then provide the closure, or the functionality of the abstraction, during assignment.
<syntaxhighlight lang="java">
Example example = (valueA, valueB) -> valueA + valueB;
sum(example);
</syntaxhighlight>
</p>
<p>
<kbd><i>"Using a function in first-class context with an expression."</i></kbd><br />
First-class context is out-of-scope for Java, which is statically-typed.
</p>
<p>
<kbd><i>"Obtaining the return value of a function."</i></kbd><br />
</p>
<syntaxhighlight lang="java">
String string = Object.methodName("rosetta", "code");
</syntaxhighlight>
<p>
<kbd><i>"Distinguishing built-in functions and user-defined functions."</i></kbd><br />
There is no ambiguity between built-in functions and user-defined functions.
</p>
<p>
<kbd><i>"Distinguishing subroutines and functions."</i></kbd><br />
Java refers to all procedures as methods.<br/>
As with other languages, such as Visual Basic, which uses <kbd>Sub</kbd>, and <kbd>Function</kbd>,
there is no ambiguity from methods which return values and those that don't.
</p>
<p>
The defining factor is within the method definition.<br/>
A return-type is declared before the method name, and <code>void</code> is used when there is no returned value.
<syntaxhighlight lang="java">
String methodA();
void methodB();
</syntaxhighlight>
</p>
<p>
<kbd><i>"Stating whether arguments are passed by value or by reference."</i></kbd><br />
The concept of pass-by-value and pass-by-reference is somewhat a redefined measure within Java.<br/>
For the most part, everything is pass-by-value; there are no pointers and dereferencing, as with C, C++, and Rust.<br/>
Although, if you're passing an object, it can be viewed as pass-by-reference, since the operation is occurring on the actual object,
and a new value is not created.<br/>
Java is essentially an language that was influenced by languages which use pass-by-reference, so it's abstraction is lacking.
</p>
<p>
<kbd><i>"Is partial application possible and how."</i></kbd><br />
Not without a closure.<br/>
I found the following example on [https://en.wikipedia.org/wiki/Partial_application#Implementations Wikipedia - Partial application].
</p>
<syntaxhighlight lang="java">
<X, Y, Z> Function<Y, Z> exampleA(BiFunction<X, Y, Z> exampleB, X value) {
return y -> exampleB.apply(value, y);
}
</syntaxhighlight>
 
 
 
<br />
 
Here is an alternate demonstration.<br />
Java does not have functions, but Java classes have "methods" which are equivalent.
 
* Calling a function that requires no arguments
<syntaxhighlight lang ="java">myMethod()</langsyntaxhighlight>
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
<syntaxhighlight lang ="java">myMethod(97, 3.14)</langsyntaxhighlight>
 
* Calling a function with optional arguments
This is possible if the method name is overloaded with different argument lists. For example:
<langsyntaxhighlight lang="java">int myMethod(int a, double b){
// return result of doing sums with a and b
}
Line 1,778 ⟶ 3,180:
int myMethod(int a){
return f(a, 1.414);
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="java">System.out.println( myMethod( 97, 3.14 ) );
System.out.println( myMethod( 97 ) );</langsyntaxhighlight>
 
* Calling a function with a variable number of arguments
This is possible if the method is defined with varargs syntax. For example:
<langsyntaxhighlight lang="java">void printAll(String... strings){
for ( String s : strings )
System.out.println( s );
}</langsyntaxhighlight>
 
The type of <tt>strings</tt> is actually a string array, but the caller just passes strings:
<langsyntaxhighlight lang="java">printAll( "Freeman" );
printAll( "Freeman", "Hardy", "Willis" );</langsyntaxhighlight>
 
To avoid ambiguity, only the last argument to a function can have varargs.
Line 1,799 ⟶ 3,201:
* Calling a function with named arguments
Not directly possible, but you could simulate this (somewhat verbosely):
<langsyntaxhighlight lang="java">int myMethod( Map<String,Object> params ){
return
((Integer)params.get("x")).intValue()
+ ((Integer)params.get("y")).intValue();
}</langsyntaxhighlight>
 
Called like this:
<langsyntaxhighlight lang="java">System.out.println( myMethod(new HashMap<String,Object>(){{put("x",27);put("y",52);}}) );</langsyntaxhighlight>
 
Yuk.
Line 1,817 ⟶ 3,219:
 
* Obtaining the return value of a function
<langsyntaxhighlight lang="java">int i = myMethod(x);</langsyntaxhighlight>
 
* Distinguishing built-in functions and user-defined functions
Line 1,827 ⟶ 3,229:
* 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:
<langsyntaxhighlight lang="java">myMethod(List<String> list){
// If I change the contents of the list here, the caller will see the change
}</langsyntaxhighlight>
 
* Is partial application possible and how
Line 1,838 ⟶ 3,240:
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.
 
<langsyntaxhighlight JavaScriptlang="javascript">var foo = function() { return arguments.length };
foo() // 0
foo(1, 2, 3) // 3</langsyntaxhighlight>
 
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.
<langsyntaxhighlight JavaScriptlang="javascript">var squares = [1, 2, 3].map(function (n) { return n * n }); // [1, 4, 9]</langsyntaxhighlight>
 
Naturally, they can also be returned, thus partial application is supported.
<syntaxhighlight lang="javascript">
<lang JavaScript>
var make_adder = function(m) {
return function(n) { return m + n }
};
var add42 = make_adder(42);
add42(10) // 52</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight JavaScriptlang="javascript">foo.toString()
"function () { return arguments.length }"
alert.toString()
"function alert() { [native code] }"</langsyntaxhighlight>
 
Arguments are passed by value, but the members of collections are essentially passed by reference and thus propagate modification.
<langsyntaxhighlight JavaScriptlang="javascript">var mutate = function(victim) {
victim[0] = null;
victim = 42;
};
var foo = [1, 2, 3];
mutate(foo) // foo is now [null, 2, 3], not 42</langsyntaxhighlight>
 
=={{header|jq}}==
jq functions are pure functions that are somewhat unusual in two respects:
Line 1,908 ⟶ 3,309:
'''Using a function in statement context'''
 
The assignment to a local variable (e.g. <tt>(2*2) as $two</tt>) is similar to a statement context in that the expression as a whole does nothing to the flow of values from its input to its output.
 
'''Using a function in first-class context within an expression'''
Line 1,936 ⟶ 3,337:
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">
<lang Julia>
# Calling a function that requires no arguments:
f() = print("Hello world!")
Line 2,027 ⟶ 3,428:
v = [4, 6, 8]
map(x -> f(x, 10), v) # v = [30, 52, 82]
</syntaxhighlight>
</lang>
 
=={{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.
<syntaxhighlight lang="kotlin">fun fun1() = println("No arguments")
<lang scala>// version 1.0.6
 
fun fun1() = println("No arguments")
 
fun fun2(i: Int) = println("One argument = $i")
Line 2,049 ⟶ 3,447:
fun fun8(x: String) = { y: String -> x + " " + y }
 
fun main(args: Array<String>) {
fun1() // no arguments
fun2(2) // fixed number of arguments, one here
Line 2,059 ⟶ 3,457:
println(1 + fun6(4, ::fun5) + 3) // first class context within an expression
println(fun5(5)) // obtaining return value
println(Mathkotlin.math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver
fun1() // calling sub-routine which has a Unit return type by default
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
}</langsyntaxhighlight>
 
{{out}}
Line 2,075 ⟶ 3,473:
20
25
2.0
3
No arguments
5.5
Line 2,081 ⟶ 3,479:
</pre>
 
=={{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}.
<syntaxhighlight lang="scheme">
 
The command
 
replace :a0 :a1 ... an-1
in expression containing some occurences of :ai
by v0 v1 ... vp-1
 
is rewritten in a prefixed parenthesized form
 
{{lambda {:a0 :a1 ... an-1}
expression containing some occurences of :ai}
v0 v1 ... vp-1}
 
so called IIFE (Immediately Invoked Function Expression), and defines an anonymous function containing a sequence of n arguments :ai, immediately invoked on a sequence of p values vi, and returning the expression in its body as so modified:
 
1) if p < n (partial application)
 
• the occurrences of the p first arguments are replaced in the function's body by the corresponding p given values,
• a function waiting for missing n-p values is created,
• and its reference is returned.
• example:
{{lambda {:x :y} ... :y ... :x ...} hello}
-> {lambda {:y} ... :y ... hello ...} // replaces :x by hello
-> LAMB_123 // the new functions's reference
• called with the value world this function will return ... world ... hello ...
 
2) if p = n (normal application)
 
• the occurences of the n arguments are replaced in the function's body by the corresponding p given values,
• the body is evaluated and the result is returned.
• example
{{lambda {:x :y} ... :y ... :x ...} hello world}
-> {{lambda {:y} ... :y ... hello ...} world} // replaces :x by hello
-> {{lambda {} ... world ... hello ...} } // replaces :y by world
-> ... world ... hello ... // the value
 
3) if p > n (variadicity)
 
• the occurrences of the n-1 first arguments are replaced in the function's body by the corresponding n-1 given values,
• the occurrences of the last argument are replaced in the body by the sequence of p-n supernumerary values,
• the body is evaluated and the result is returned.
• example:
{{lambda {:x :y} ... :y ... :x ...} hello world good morning}
-> {{lambda {:y} ... :y ... hello ...} world good morning}
-> {{lambda {} ... world good morning ... hello ...}}
-> ... world good morning ... hello ... // the value
 
More can be seen in http://lambdaway.free.fr/lambdawalks/?view=lambda
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
fp.noArgs = () -> \!
fp.noArgs()
 
# For user defined-functions, the argument count is not checked: If too many arguments were provided, they are ignored. If not enough arguments were provided, the last argument will be duplicated (If none was provided, VOID values will be filled in). [This process is is referred to as implict argument duplication]
fp.noArgs(42) # No Error nor Warning
 
fp.fixArgs = ($x, $y) -> \!
fp.fixArgs(1, 2)
 
fp.fixArgs(2) # Fix args will be called with $x=2 and $y=2
fp.fixArgs() # Fix args will be called with $x=VOID and $y=VOID
 
# fn.argCntX (X must be replaced with 0, 1, 2, 3, 4, or 5) can be used to force the caller to provided the exact argument count
# fn.argCntX must be called with the function to apply the constraint to and will return a new function
fp.realFixArgs = fn.argCnt2(fp.fixArgs)
fp.realFixArgs(1, 2)
 
fp.realFixArgs() # Error
fp.realFixArgs(1) # Error
fp.realFixArgs(1, 2, 3) # Error
 
# Arrays can be unpacked in function calls
&values $= [1, 2]
fp.fixArgs(&values...) # Fix args will be called with $x=1 and $y=2
 
 
# In Lang there are text and array varags parameters
fp.varArgsText = ($text...) -> \!
fp.varArgsText(1) # Var args text will be called with "1"
fp.varArgsText(1, 2) # Var args text will be called with "1, 2"
fp.varArgsText(1,2) # Var args text will be called with "1,2"
fp.varArgsText(1,text ,3) # Var args text will be called with "1,text ,3"
 
fp.varArgsArray = (&args...) -> \!
fp.varArgsArray(1) # Var args array will be called with [1]
fp.varArgsArray(1, 2) # Var args array will be called with [1, 2]
fp.varArgsArray(1,2) # Var args array will be called with [1, 2]
fp.varArgsArray(1,text ,3) # Var args array will be called with [1, text, 3]
 
# Functions with named arguments can not be created
 
# Using a function in a statement context
$x = fp.fixArgs(1, 2)
 
# Functions (Even predefined and linker functions) can be used as values
fp.retAFunc = () -> {
return ($x) -> \!
}
fp.func = fp.retAFunc()
fp.func(2)
 
# Multiple call-expressions can be used directly
fp.retAFunc()(2)
 
fp.retAFunc = () -> return fn.println
fp.retAFunc()(test, values)
 
fp.retAFunc = () -> return ln.loadModule
fp.retAFunc()(x.lm) # Error, because file not found
 
# The return value or the thrown error can be obtained with the assignment operator
fp.inc2 = ($x) -> return parser.op($x + 2)
$ret = fp.inc2(40) # $ret is 42
 
# Built-in (They are called predefined functions in Lang) start with the "func." or "fn." prefix wheras user-defined functions start with "fp."
# Linker functions start with "linker." or "ln."
# Predefined and linker functions can be stored in a user-defined function
fp.userDefinedFunc = fn.println
fp.userDefinedFunc(Called println)
 
# In Lang there are no subroutines
 
# In Lang functions can have call-by-pointer values
# $ptr is a pointer to the called value
fp.callByPtr = ($[ptr]) -> \!
fp.callByPtr(42) # This will create a pointer to an anonymous value, therefor it can not be changed
 
fp.inc2 = ($[ptr]) -> $*ptr += 2
fp.inc2(40) # Error
$val = 40
fp.inc2($val) # $val is now 42
 
# Functions can also be called with pointers directly
fp.inc2 = ($ptr) -> $*ptr += 2
fp.inc2(40) # Multiple Errors (Value will be dereferenced as NULL -> + is not defined for NULL and INT AND anonymous values can not be changed)
 
$val = 40
fp.inc2($[val]) # $val is now 42
 
# Partial apllication of functions is possible by using combinator functions
# The simplest combinator function-family is the A combinator family (Other families change the order of arguments, can call multiple function, ...)
fp.partialAdd = fn.combA2(fn.add) # When all arguments for fn.combA2(a, b, c) are provided, the execution of a(b, c) will begin
fp.add42 = fp.partialAdd(42) # Creates a function which still needs 1 argument
fp.add42(2) # Will return 44
 
# Without the use of fn.argCntX 0 args can also be provied
fp.add42()()()(2) # Will also return 44
</syntaxhighlight>
 
===Special function-related features===
<syntaxhighlight lang="lang">
# The function argument auto un-pack operator (▲ or +|) can be used to create a function which must be called with an array value that is automatically unpacked
fp.fixArgs = ($x, $y) -> \!
fp.unpackingFixArgs $= +|fp.fixArgs
fp.unpackingFixArgs(&values) # Fix args will be called with $x=1 and $y=2
 
# The function argument auto pack operator (▼ or -|) can be used to cerate a function wich must be called with varargs and will call the original function with a single array argument
fp.arrayArg = (&arr) -> \!
fp.packingArrayArg $= -|fp.arrayArg
fp.packingArrayArg(1, 2) # Array arg will be called with [1, 2]
 
# Functions can also be called with the pipe operators (|, >>, and >>>)
# The "|" and ">>" pipe operators are identical apart from the operator precedence
# The ">>>" pipe operator automatically unpacks array values
fp.func = ($x) -> \!
parser.op(42 | fp.func) # fp.func is called with 42
parser.op(42 >> fp.func) # fp.func is called with 42
parser.op([42] >>> fp.func) # fp.func is called with 42
 
# Function calls can be concatinated with the concat operator (|||)
fp.incAndPrint $= fn.inc ||| fn.println # Calling fp.incAndPrint($x) has the same effect as calling fn.println(fn.inc($x))
fp.incAndPrint(2) # Prints 3
 
# The pow operator can be used to call a function multiple times in succession
# This works only with exponents >= 0 (If the exponent is 0 a function will be returned, that always returns VOID)
fp.voidFunc $= fn.inc ** 0
fp.voidFunc(2) # Returns VOID
 
fn.pow(fn.inc, 1)(2) # Returns 3
fn.pow(fn.inc, 2)(2) # Returns 4
fn.pow(fn.inc, 3)(2) # Returns 5
fn.pow(fn.inc, 10)(2) # Returns 12
</syntaxhighlight>
 
=={{header|langur}}==
User-defined and built-in functions can be called using parentheses.
 
Built-in functions can also be called using an "unbounded list," which ends at a line return, EOF, closing parenthesis, curly brace, or square bracket, or before a comma preceding a line return.
 
=== parentheses ===
<syntaxhighlight lang="langur">.x()
# call user-defined function</syntaxhighlight>
 
<syntaxhighlight lang="langur">write(.key, ": ", .value)
# call built-in with parentheses</syntaxhighlight>
 
=== unbounded lists ===
<syntaxhighlight lang="langur">write .key, ": ", .value
# call built-in with unbounded list</syntaxhighlight>
 
<syntaxhighlight lang="langur">writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4]
# unbounded lists on writeln and join
# later function join takes remaining arguments</syntaxhighlight>
 
<syntaxhighlight lang="langur">writeln "numbers: ", join(", ", [.a1, .a2, .a3, .a4]), " === "
# unbounded list on writeln
# join using parentheses so it doesn't take remaining arguments</syntaxhighlight>
 
<syntaxhighlight lang="langur">val .sum = foldfrom(
fn(.sum, .i, .c) { .sum + number(.c, 36) * .weight[.i] },
0,
pseries len .code,
split .code,
)
# 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</syntaxhighlight>
 
=={{header|Latitude}}==
 
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.
 
<syntaxhighlight lang="text">foo (1, 2, 3). ; (1) Ordinary call
foo (). ; (2) No arguments
foo. ; (3) Equivalent to (2)
foo (1). ; (4) Single-argument function
foo 1. ; (5) Equivalent to (4)
foo (bar). ; (6) Parentheses necessary here since bar is not a literal
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.
 
<syntaxhighlight lang="text">myProc := proc { foo. }.
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.
 
<syntaxhighlight lang="text">myProc1 := #'foo shield.
myProc2 := proc { foo. }.
myProc3 := proc { foo. } shield.</syntaxhighlight>
 
All three of the above procedures will act the same.
=={{header|LFE}}==
 
Line 2,086 ⟶ 3,733:
 
In some module, define the following:
<langsyntaxhighlight lang="lisp">
(defun my-func()
(: io format '"I get called with NOTHING!~n"))
</syntaxhighlight>
</lang>
 
Then you use it like so (depending upon how you import it):
<langsyntaxhighlight lang="lisp">
> (my-func)
I get called with NOTHING!
ok
</syntaxhighlight>
</lang>
 
'''Calling a function with a fixed number of arguments:'''
In some module, define the following:
<langsyntaxhighlight lang="lisp">
(defun my-func(a b)
(: io format '"I got called with ~p and ~p~n" (list a b)))
</syntaxhighlight>
</lang>
 
Then you use it like so:
<langsyntaxhighlight lang="lisp">
> (my-func '"bread" '"cheese")
I got called with "bread" and "cheese"
ok
</syntaxhighlight>
</lang>
 
'''Calling a function with optional arguments or calling a function with a variable number of arguments:'''
Line 2,118 ⟶ 3,765:
* One can define multiple functions so that it ''appears'' that one is calling a function with optional or a variable number of arguments:
 
<langsyntaxhighlight lang="lisp">
(defmodule args
(export all))
Line 2,133 ⟶ 3,780:
(defun my-func (a b c)
(: io format '"~p ~p ~p~n" (list a b c)))
</syntaxhighlight>
</lang>
 
Here is some example usage:
<langsyntaxhighlight lang="lisp">
> (slurp '"args.lfe")
#(ok args)
Line 2,153 ⟶ 3,800:
> (my-func '"apple" '"banana" '"cranberry" '"bad arg")
exception error: #(unbound_func #(my-func 4))
</langsyntaxhighlight>
 
'''Calling a function with named arguments:'''
Line 2,163 ⟶ 3,810:
 
'''Using a function in statement context:'''
<langsyntaxhighlight lang="lisp">
...
(cond ((== count limit) (hit-limit-func arg-1 arg-2))
((/= count limit) (keep-going-func count)))
...
</syntaxhighlight>
</lang>
 
'''Using a function in first-class context within an expression:'''
 
From the LFE REPL:
<langsyntaxhighlight lang="lisp">
> (>= 0.5 (: math sin 0.5))
true
</syntaxhighlight>
</lang>
 
'''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:
<langsyntaxhighlight lang="lisp">
(let ((x (: math sin 0.5)))
...)
</syntaxhighlight>
</lang>
 
'''Distinguishing built-in functions and user-defined functions:'''
 
* There is no distinction made in LFE/Erlang between functions that are built-in and those that are not.
* "Built-in" for LFE/Erlang usually can be figured out: if a function has the module name <code>erlang</code>, e.g., <code>(: erlang list_to_integer ... )</codcode>, then it's built-in.
* Most of the functions that come with LFE/Erlang are not even in the <code>erlang</code> module, but exist in other modules (e.g., <code>io</code>, <code>math</code>, etc.) and in OTP.
* One uses user/third-party modules in exactly the same way as one uses built-ins and modules that come with the Erlang distribution.
Line 2,211 ⟶ 3,858:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'Call a function - Liberty BASIC
 
Line 2,254 ⟶ 3,901:
'Is partial application possible and how
'impossible
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
 
*Calling a function that requires no arguments
<langsyntaxhighlight lang="lingo">foo()
-- or alternatively:
call(#foo, _movie)</langsyntaxhighlight>
 
*Calling a function with a fixed number of arguments
<langsyntaxhighlight lang="lingo">foo(1,2,3)
-- or alternatively:
call(#foo, _movie, 1, 2, 3)</langsyntaxhighlight>
 
*Calling a function with optional arguments
<langsyntaxhighlight lang="lingo">on foo (a, b)
if voidP(b) then b = 1
return a * b
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">put foo(23, 2)
-- 46
put foo(23)
-- 23</langsyntaxhighlight>
 
*Calling a function with a variable number of arguments
<langsyntaxhighlight lang="lingo">on sum ()
res = 0
repeat with i = 1 to the paramCount
Line 2,285 ⟶ 3,931:
end repeat
return res
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">put sum (1,2,3)
-- 6</langsyntaxhighlight>
 
*Calling a function with named arguments
Line 2,295 ⟶ 3,941:
*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:
<langsyntaxhighlight lang="lingo">----------------------------------------
-- One of the five native iterative methods defined in ECMAScript 5
-- @param {list} tList
Line 2,314 ⟶ 3,960:
on doubleInt (n)
return n*2
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">l = [1,2,3]
put map(l, #doubleInt)
-- [2, 4, 6]</langsyntaxhighlight>
 
*Obtaining the return value of a function
<langsyntaxhighlight lang="lingo">x = foo(1,2)</langsyntaxhighlight>
 
*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:
<langsyntaxhighlight lang="lingo">on getAllUserFunctions ()
res = []
repeat with i = 1 to _movie.castlib.count
Line 2,340 ⟶ 3,986:
end repeat
return res
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">put getAllUserFunctions()
-- [#sum, #double, #getAllUserFunctions]</langsyntaxhighlight>
 
*Distinguishing subroutines and functions
Line 2,349 ⟶ 3,995:
*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:
<langsyntaxhighlight lang="lingo">on double (someList)
cnt = someList.count
repeat with i = 1 to cnt
someList[i] = someList[i] * 2
end repeat
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">l = [1,2,3]
double(l)
put l
Line 2,363 ⟶ 4,009:
double(l.duplicate())
put l
-- [1, 2, 3]</langsyntaxhighlight>
 
=={{header|Little}}==
 
Line 2,370 ⟶ 4,015:
local fuctions.
 
<langsyntaxhighlight Clang="c">// Calling a function that requires no arguments
void foo() {puts("Calling a function with no arguments");}
foo();
Line 2,404 ⟶ 4,049:
puts (a);
puts (b);
}</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight 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
fixed() --> nil nil nil
Line 2,439 ⟶ 4,083:
-- There is no separate notion of subroutines
-- Built-in functions are not easily distinguishable from user-defined functions
</syntaxhighlight>
</lang>
 
=={{header|Luck}}==
<langsyntaxhighlight lang="luck">/* Calling a function that requires no arguments */
f();;
 
Line 2,484 ⟶ 4,127:
 
/* 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);;</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<pre>
===Standard Call of Modules/Functions===
// Calling a function that requires no arguments
In M2000 we can use arrays, functions and subroutines with same name. Using @ we can direct interpreter to use function. Using Gosub we direct interpreter to call a subroutine. These happen at module/function level.
ModuleA ' introduce a namespace can have modules/functions/subs, anything inside, and threads.
A Subroutine is code inside Modules/Functions where all definitions in module/function are visible. Modules and functions can call own modules/functions or global modules/functions. Functions can use recursion. Module with standard calling can't use recursion (need to use Call nameOfModule to call itself).
Call FunctionA() ' introduce a namespace can have modules/functions/subs, anything inside.
Call LambdaA() ' introduce a namespace can have modules/functions/subs, anything inside.
SubAlfa() ' subroutine this has the same scope as the caller, we can use Local statement to shadow variables/arrays
Print @Simple() ' simple function this has the same scope as the caller, we can use Local statement to shadow variables/arrays
Gosub labelA ' Statement Return used to return from a gosub, no arguments and no local statement used, the code is like any other code in the module/function/lambda scope. No jump out of scope allowed.
Gosub 10020 ' Statement Return used to return from a gosub,, no arguments and no local statement used, the code is like any other code in the module/function/lambda scope. No jump out of scope allowed.
// Calling a function with a fixed number of arguments
ModuleA 100
SubAlfa(100) ' subroutine
Print @Simple(100) ' simple function
Call FunctionA(100)
Call LambdaA(100)
// Calling a function with optional arguments
ModuleA ?,4
SubAlfa(?) ' subroutine
Print @Simple(?) ' simple function
Call FunctionA(,4)
Call LambdaA(,4)
// Calling a function with a variable number of arguments
Call FunctionA(1,2,3,4,5)
Call LambdaA(1,2,3,4,5)
// Calling a function with named arguments
ModuleA %X=10, %Z=20
// Using a function in statement context
Module A
SubAlfa()
Call Void FunctionA()
Call Void LambdaA()
// Using a function in first-class context within an expression
Print (lambda (x,y)->{=x**y}(2,3))*8=64
// Obtaining the return value of a function
A%=FunctionA%() ' integer part from any numeric type. Also A% if get decimals convert to integer using school rounding (0.5, so 3.5 is 4, 2.5 is 3)
A=FunctionA() ' numeric or object
A$=FunctionA$() ' string or object which return string
A=LambdaA()
A$=LambdaA$()
A=@SimpleA()
A$=@SimpleA$()
// Distinguishing built-in functions and user-defined functions
Def Cos(x)=100*X ' change the build in
Print Cos(3), @Cos(3) ' @Cos() is the build in anyway
' we can't use simple function with same name as a bultin function.
// Distinguishing subroutines and functions
Name without parenthesis like a command or statement is a Module
Name with parentesis without operator is a Sub
Name with parenthesis in an expression is a function or array (array come first), using a(*10) we say that it is function even an array a() exist.
Name with @ as first symbol and parenthesis like @alfa() is a simple function unless has a builtin name, so is that function.
// Stating whether arguments are passed by value or by reference
Default:By Value
By Reference: Using & at both sides (caller and calee)
Function Alfa(&x) {
=X : X++
}
Print Alfa(&counter)
Subs and Simple Functions not need a by reference pass because they are in the same scope from the caller, so actuall we pass by value to be local to those entities. But we can use by reference, except for static variables, and array items. Those can only passed by reference on modules and nornal functions and lambdas (which are normal functions plus more).
 
// Is partial application possible and how
 
A=Lambda (X) -> {
<lang M2000 Interpreter>
=Lambda X (Y) -> {
Module CheckIt {
=Y**X
Dim a(4)=100
}
Def a(x)=x**2
Print a(2), a(@2)
Gosub a(4)
Print "End"
Sub a(x)
Print "This is sub a()", x
End Sub
}
Cube=A(3) : Square=A(2)
CheckIt
Print Cube(2)=8, Square(2)=4
Call CheckIt
\\ both module and function can exist with same name
Function CheckIt {
Dim a(4)=100
Def a(x)=x**2
Print a(2), a(@2)
Gosub a(4)
Print "End"
Sub a(x)
Print "This is sub a()", x
End Sub
}
Call CheckIt()
Call Function Checkit
\\ if a function return a non zero number then we get error with value the returned number. Using Void we drop any return value, so no error happen.
Call Void CheckIt()
Call Void Function Checkit
\\ subs are part of modules/functions (there are no global subs, but there is a way to share definitions modules from parent module).
Module CheckSub {
M=1
a(100) ' 400
a(100) ' 800
Module Child {
M=1
a(100) ' 400
a(100) ' 800
}
Child
Sub a(x)
b(x*4)
M++
End Sub
Sub b(x)
Print x*M
End Sub
}
CheckSub
 
OOP: Functions/Modules can be members of objects.
</lang>
Objects may have a name (they live until code get out of scope)
Objects may don't have a name but one or more pointers, (they live until counting references are zero)
 
ObjectA.moduleA is a call to an object method (a module)
===Call Local===
pointerA=>moduleA is a call to an object by a pointer
Using standard call, a call to a module or a function open a new namespace, so we can use local variables. But what if we want to call a function as a subroutine, where the namespace is the same as the module/function where we define it.
So we have to ''read new'' to make K new, not reading the same K in module Checkit. We have to use Local N to shadow N in module Checkit. After the call to Alfa, all new definitions erased. The sane hold for call Checkit, anything defined there erased after the call. Only Stack return. A Call Local use new stack, the same as the calling of function in expression (a standard Call to module or function, using Call statement use parent stack)
 
An object may return values, and may accept parameters too. Also objects if they didn't return values other than a copy of them can be use operators defined as object functions.
<lang M2000 Interpreter>
Module CheckIt {
M=100
K=5
N=200
Function Alfa {
Read New K
Local N=3
M++
Print M*K/3
}
Call Local Alfa(30) ' print 1010
Print M=101, K=5, N=200
}
CheckIt
</lang>
 
Objects may have events and fire them using Call Event "simpleevent", param1, param2...
===Using Event Object===
We have to define the type of arguments to event object. We can add functions to event and we can remove them, except one internal (optional defined using Function {} without a read command)
<lang M2000 Interpreter>
Module CheckIt (&P){
Event Alfa {
Read X, &M
Function {
Print X, M
}
}
Function Other (a, &b) {
b++
Print a*b
}
Event Alfa New &Other()
Call Event Alfa, 3, &P
\\ Print 3 10 \\ form internal function in Event Alfa
\\ Print 33 \\ from Other()
Print P=11
Push ALfa
}
M=10
Checkit &M
Read ReturnedEventObject
Call Event ReturnedEventObject, 2, &M
\\ Print 2 11 \\ form internal function in Event Alfa
\\ Print 24 \\ from Other(), which is a closure to event
Print M=12
</lang>
 
Functions and lambda (not simple functions), and object functions can be passed by reference as parameters.
 
===Call a reference to Function===
<lang M2000 Interpreter>
Module Checkit {
Group Alfa {
x=10
Function Beta {
=.x
.x++
}
}
Module PassRef (&n()) {
Print n()
}
PassRef &Alfa.Beta()
Print Alfa.x=11
}
Call Checkit
</lang>
 
===Light Event Function===
<lang M2000 Interpreter>
Module Checkit {
Group WithEvents Alfa {
Event "AddOne"
x=10
Function Beta {
=.x
.PrintIt .x+1
.x++
}
Module PrintIt (x) {
Call Event "AddOne", x
}
}
Module PassRef (&n()) {
z=n()
}
z=500
k=0
Function Alfa_AddOne (new z) {
\\ interpreter make a line: Read New Z
k+=z
Print z
}
PassRef &Alfa.Beta()
Print k=11, z=500
}
Call Checkit
</lang>
 
</pre>
=={{header|Maple}}==
Calling a function with no arguments:<syntaxhighlight lang Maple="maple"> f()</langsyntaxhighlight>
Calling a function with a fixed number of arguments:<langsyntaxhighlight Maplelang="maple">f(1,sin(x), g -> int(g(t),t=0..1)</langsyntaxhighlight>
Calling a function with optional arguments: <langsyntaxhighlight Maplelang="maple">f(1, sin(x), g -> int(g(t),t=0..1)</langsyntaxhighlight>
Calling a function with a variable number of arguments: <langsyntaxhighlight Maplelang="maple">f(1, sin(x), g -> int(g(t),t=0..1)</langsyntaxhighlight>
Calling a function with named arguments:<langsyntaxhighlight Maplelang="maple">f(a,b,method = foo)</langsyntaxhighlight>
Calling a function in a statements context:<syntaxhighlight lang Maple="maple">f(a); f(b);</langsyntaxhighlight>
Using a function in first-class context within an expression:<syntaxhighlight lang Maple="maple">f(a) + g(b)</langsyntaxhighlight>
Obtaining the return value of a function:<langsyntaxhighlight Maplelang="maple"> x := f(1)</langsyntaxhighlight>
Distinguishing built-in functions and user-defined functions:
<langsyntaxhighlight Maplelang="maple">> type( op, 'builtin' );
true
</syntaxhighlight>
</lang>
Distinguishing subroutines and functions: There is no distinction.
 
Line 2,665 ⟶ 4,232:
 
Partial application is supported by the <code>curry</code> and <code>rcurry</code> commands.
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Calling a function that requires no arguments:
<syntaxhighlight lang Mathematica="mathematica">f[]</langsyntaxhighlight>
 
Calling a function with a fixed number of arguments:
<syntaxhighlight lang Mathematica="mathematica">f[1,2]</langsyntaxhighlight>
 
Calling a function with optional arguments:
<syntaxhighlight lang Mathematica="mathematica">f[1,Option1->True]</langsyntaxhighlight>
 
Calling a function with a variable number of arguments:
<langsyntaxhighlight Mathematicalang="mathematica">f[1,Option1->True]
f[1,Option1->True,Option2->False]</langsyntaxhighlight>
 
Calling a function with named arguments:
<langsyntaxhighlight Mathematicalang="mathematica">f[Option1->True,Option2->False]</langsyntaxhighlight>
 
Using a function in statement context:
<langsyntaxhighlight Mathematicalang="mathematica">f[1,2];f[2,3]</langsyntaxhighlight>
 
Using a function in first-class context within an expression:
<syntaxhighlight lang Mathematica="mathematica">(#^2)&[3];</langsyntaxhighlight>
 
The return value of a function can be formally extracted using Return[]
Line 2,693 ⟶ 4,259:
No formal distinction between subroutines and functions.
Arguments can be passed by value or by reference.
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
% Calling a function that requires no arguments
function a=foo();
Line 2,745 ⟶ 4,310:
% 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.
</syntaxhighlight>
</lang>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">// function with no arguments
no_args()
 
// function with fixed amount of arguments
three_args(a, b, c)
 
// nanoquery does not support optional, variable, or named arguments
 
// obtaining a return value
value = returns_value()
 
// checking if a function called "func" is user-defined
try
type(func)
println "func is user-defined"
catch
println "func is a built-in or doesn't exist"
end</syntaxhighlight>
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">// no arguments
f()
 
Line 2,804 ⟶ 4,387:
def h = f(_, 2)
def a = g(3) // equivalent to: def a = f(2, 3)
def b = h(3) // equivalent to: def b = f(3, 2)</langsyntaxhighlight>
 
=={{header|Nim}}==
Translated from Python, when possible:
<langsyntaxhighlight lang="nim">proc no_args() =
discard
# call
Line 2,850 ⟶ 4,432:
let x = return_something(19) + 10
let y = 19.return_something() + 10
let z = 19.return_something + 10</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
* Calling a function that requires no arguments:
 
<syntaxhighlight lang ="ocaml">f ()</langsyntaxhighlight>
 
(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 2,862 ⟶ 4,443:
* Calling a function with a fixed number of arguments:
 
<syntaxhighlight lang ="ocaml">f 1 2 3</langsyntaxhighlight>
 
* Calling a function with optional arguments:
Line 2,868 ⟶ 4,449:
For a function that has this signature:
 
<langsyntaxhighlight lang="ocaml">val f : ?a:int -> int -> unit</langsyntaxhighlight>
 
here is how to call it with or without the first argument omited:
 
<langsyntaxhighlight lang="ocaml">f 10
f ~a:6 10</langsyntaxhighlight>
 
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>:
 
<langsyntaxhighlight lang="ocaml">g ()
g ~b:1.0 ()</langsyntaxhighlight>
 
* Calling a function with a variable number of arguments:
Line 2,890 ⟶ 4,471:
Named arguments are called '''labels'''.
 
<syntaxhighlight lang ="ocaml">f ~arg:3</langsyntaxhighlight>
 
If a variable has the same name than the label we can use this simpler syntax:
 
<langsyntaxhighlight lang="ocaml">let arg = 3 in
f ~arg</langsyntaxhighlight>
 
* Using a function in statement context:
 
<syntaxhighlight lang ="ocaml">(* TODO *)</langsyntaxhighlight>
 
* Using a function in first-class context within an expression:
Line 2,907 ⟶ 4,488:
* Obtaining the return value of a function:
 
<langsyntaxhighlight lang="ocaml">let ret = f ()
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 v, _ = f () (* if we want to ignore one of the returned value *)</langsyntaxhighlight>
 
* Distinguishing built-in functions and user-defined functions:
Line 2,929 ⟶ 4,510:
 
With partial application, the arguments are applied in the same order than they are defined in the signature of the function, except if there are labeled arguments, then it is possible to use these labels to partially apply the arguments in any order.
 
=={{header|Oforth}}==
 
Line 2,937 ⟶ 4,517:
 
If f is a function and c b a ares objects :
<syntaxhighlight lang Oforth="oforth">a b c f</langsyntaxhighlight>
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 :
<syntaxhighlight lang Oforth="oforth">f(a, b, c)</langsyntaxhighlight>
 
Intepreter will replace this second syntax by the first one. It is only "sugar"...
 
<langsyntaxhighlight Oforthlang="oforth">a b c f
a b f(c)
a f(b, c)
f(a, b, c)</langsyntaxhighlight>
 
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 2,954 ⟶ 4,534:
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 :
<syntaxhighlight lang Oforth="oforth">a b c r m</langsyntaxhighlight>
will call m with r as its receiver.
It is also possible to use the same "sugar" notation used by functions :
<langsyntaxhighlight Oforthlang="oforth">r m(a, b, c)</langsyntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
<lang ol>
; note: sign "==>" indicates expected output
 
Line 2,966 ⟶ 4,545:
(define (no-args-function)
(print "ok."))
)
 
(no-args-function)
Line 2,976 ⟶ 4,554:
(print "a: " a)
(print "b: " b))
)
 
(two-args-function 8 13)
Line 2,992 ⟶ 4,569:
(if (less? 1 (length args))
(print "c: " (cadr args)))
; etc...
)
 
Line 3,016 ⟶ 4,593:
 
;;; Calling a function with named arguments
; /no named arguments "from the box" is provided, but it can be easily simulated using builtin mapsassociative arrays (named "ff")
(define (named-args-function args)
(print "a: " (get args 'a 8)) ; 8 is default value if no variable value given
(print "b: " (get args 'b 13)); same as above
)
 
Line 3,028 ⟶ 4,605:
; ==> a: 3
; ==> b: 13
; or nicer (and shorter) form available from ol version 2.1
(named-args-function (list->ff '((b . 7))))
(named-args-function '{a 3})
; ==> a: 3
; ==> b: 13
(named-args-function '{b 7})
; ==> a: 8
; ==> b: 7
(named-args-function (list->ff '(({a . 3) ( b . 7)))})
; ==> a: 3
; ==> b: 7
Line 3,046 ⟶ 4,627:
; ==> -1
 
;;; Using a function in statement context
(let ((function (lambda (x) (* x x))))
(print (function 4))
; ==> 16
;(print (function 4))
; ==> What is 'function'?
 
;;; Obtaining the return value of a function
Line 3,056 ⟶ 4,643:
; ==> ok.
; ==> 123
 
; actually
;;; Obtaining the return value of a function while breaking the function execution (for example infinite loop)
(print
(call/cc (lambda (return)
(let loop ((n 0))
(if (eq? n 100)
(return (* n n)))
(loop (+ n 1))))))) ; this is infinite loop
; ==> 10000
 
 
Line 3,066 ⟶ 4,661:
 
(define plus (make-partial-function +))
(define minus (make-partial-function -))
 
(plus 2 3)
; ==> 5
(define minus (make-partial-function -))
(minus 2 3)
; ==> -1
 
 
; TBD:
;;; Using a function in statement context
;;; Using a function in first-class context within an expression
;;; Obtaining the return value of a function
;;; Distinguishing built-in functions and user-defined functions
; ol has no builtin functions but only eight builtin forms: quote, values, lambda, setq, letq, ifeq, either, values-apply.
; all other functions is "user-defined", and some of them defined in base library, for example (scheme core) defines if, or, and, zero?, length, append...
 
;;; Distinguishing subroutines and functions
; Both subroutines and functions is a functions in Ol.
;;; Stating whether arguments are passed by value or by reference
; Btw, the "subroutine" has a different meaning in Ol - the special function that executes simultaneously in own context. The intersubroutine messaging mechanism is provided, sure.
 
</lang>
 
;;; 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.
</syntaxhighlight>
=={{header|ooRexx}}==
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()
Exit
daTe: Return 'my date' </syntaxhighlight>
{{out}}
<pre>H:\>rexx fdate
31 Mar 2022
my date</pre>
=={{header|PARI/GP}}==
Calling a function is done in GP by writing the name of the function and the arguments, if any, in parentheses. As of version 2.5.0, function calls must use parentheses; some earlier versions allowed functions with an arity of 0 to be called without parentheses. However built-in constants (which are implicit functions of the current precision) can still be called without parentheses.
Line 3,089 ⟶ 4,695:
 
Functions can be used when statements would be expected without change.
<langsyntaxhighlight lang="parigp">f(); \\ zero arguments
sin(Pi/2); \\ fixed number of arguments
vecsort([5,6]) != vecsort([5,6],,4) \\ optional arguments
Line 3,095 ⟶ 4,701:
call(Str, ["gg", 1, "hh"]) \\ variable number of arguments in a vector
(x->x^2)(3); \\ first-class
x = sin(0); \\ get function value</langsyntaxhighlight>
 
Built-in functions are like user-defined functions in current versions. In older versions built-in functions cannot be passed as closures.
 
Most arguments are passed by reference. Some built-in functions accept arguments (e.g., flags) that are not <code>GEN</code>s; these are passed by value or reference depending on their [[C]] type. See the User's Guide to the PARI Library section 5.7.3, "Parser Codes".
=={{header|Pascal}}==
''see also: [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]]''
 
Calling a nullary function and obtaining its return value:
=={{Header|Perl}}==
<syntaxhighlight lang="pascal">foo</syntaxhighlight>
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).
* optional arguments<!-- except for certain _built-in_ _procedures_ [no functions!] -->
* variable number of arguments<!-- except for certain built-in _procedures_ [no functions!] -->
* named arguments
* using a function call as a statement
* distinguishing built-in functions and user-defined functions
* distinguishing subroutines and functions
* stating ''at the call site'' whether arguments are passed by value or by reference
* partial application
=={{header|Perl}}==
The most common syntax; simply calls the function foo on the argument(s) provided.
<langsyntaxhighlight lang="perl">foo(); # Call foo on the null list
&foo(); # Ditto
foo($arg1, $arg2); # Call foo on $arg1 and $arg2
&foo($arg1, $arg2); # Ditto; ignores prototypes</langsyntaxhighlight>
Call foo() as a bareword. Only works after the function has been declared, which
can be done normally or with the use subs pragma.
<syntaxhighlight lang ="perl">foo;</langsyntaxhighlight>
Call foo() with the current values of @_<syntaxhighlight lang ="perl">&foo;</langsyntaxhighlight>
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;</langsyntaxhighlight>
For subroutines stored in references (anonymous subroutines).<langsyntaxhighlight lang="perl">&$fooref('foo', 'bar');
&{$fooref}('foo', 'bar');
$fooref->('foo', 'bar');</langsyntaxhighlight>
 
=={{header|Perl 6}}==
Fundamentally, nearly everything you do in Perl 6 is a function call if you look hard enough.
At the lowest level, a function call merely requires a reference to any
kind of invokable object, and a call to its <tt>postcircumfix:&lt;( )&gt;</tt> method.
However, there are various forms of sugar and indirection that you
can use to express these function calls differently. In particular,
operators are all just sugar for function calls.
 
Calling a function that requires no arguments:
 
<lang perl6>foo # as list operator
foo() # as function
foo.() # as function, explicit postfix form
$ref() # as object invocation
$ref.() # as object invocation, explicit postfix
&foo() # as object invocation
&foo.() # as object invocation, explicit postfix
::($name)() # as symbolic ref</lang>
 
Calling a function with exactly one argument:
 
<lang perl6>foo 1 # as list operator
foo(1) # as named function
foo.(1) # as named function, explicit postfix
$ref(1) # as object invocation (must be hard ref)
$ref.(1) # as object invocation, explicit postfix
1.$foo # as pseudo-method meaning $foo(1) (hard ref only)
1.$foo() # as pseudo-method meaning $foo(1) (hard ref only)
1.&foo # as pseudo-method meaning &foo(1) (is hard foo)
1.&foo() # as pseudo-method meaning &foo(1) (is hard foo)
1.foo # as method via dispatcher
1.foo() # as method via dispatcher
1."$name"() # as method via dispatcher, symbolic
+1 # as operator to prefix:<+> function</lang>
 
Method calls are included here because they do eventually dispatch to a true
function via a dispatcher. However, the dispatcher in question is not going
to dispatch to the same set of functions that a function call of that name
would invoke. That's why there's a dispatcher, after all. Methods are declared
with a different keyword, <tt>method</tt>, in Perl 6, but all that does is
install the actual function into a metaclass. Once it's there, it's merely
a function that expects its first argument to be the invocant object. Hence we
feel justified in including method call syntax as a form of indirect function call.
 
Operators like <tt>+</tt> also go through a dispatcher, but in this case it is
multiply dispatched to all lexically scoped candidates for the function. Hence
the candidate list is bound early, and the function itself can be bound early
if the type is known. Perl 6 maintains a clear distinction between early-bound
linguistic constructs that force Perlish semantics, and late-bound OO dispatch
that puts the objects and/or classes in charge of semantics. (In any case, <tt>&foo</tt>,
though being a hard ref to the function named "foo", may actually be a ref to
a dispatcher to a list of candidates that, when called, makes all the candidates behave as a single unit.)
 
Calling a function with exactly two arguments:
 
<lang perl6>foo 1,2 # as list operator
foo(1,2) # as named function
foo.(1,2) # as named function, explicit postfix
$ref(1,2) # as object invocation (must be hard ref)
$ref.(1,2) # as object invocation, explicit postfix
1.$foo: 2 # as pseudo-method meaning $foo(1,2) (hard ref only)
1.$foo(2) # as pseudo-method meaning $foo(1,2) (hard ref only)
1.&foo: 2 # as pseudo-method meaning &foo(1,2) (is hard foo)
1.&foo(2) # as pseudo-method meaning &foo(1,2) (is hard foo)
1.foo: 2 # as method via dispatcher
1.foo(2) # as method via dispatcher
1."$name"(2) # as method via dispatcher, symbolic
1 + 2 # as operator to infix:<+> function</lang>
 
Optional arguments don't look any different from normal arguments.
The optionality is all on the binding end.
 
Calling a function with a variable number of arguments (varargs):
 
<lang perl6>foo @args # as list operator
foo(@args) # as named function
foo.(@args) # as named function, explicit postfix
$ref(@args) # as object invocation (must be hard ref)
$ref.(@args) # as object invocation, explicit postfix
1.$foo: @args # as pseudo-method meaning $foo(1,@args) (hard ref)
1.$foo(@args) # as pseudo-method meaning $foo(1,@args) (hard ref)
1.&foo: @args # as pseudo-method meaning &foo(1,@args)
1.&foo(@args) # as pseudo-method meaning &foo(1,@args)
1.foo: @args # as method via dispatcher
1.foo(@args) # as method via dispatcher
1."$name"(@args) # as method via dispatcher, symbolic
@args X @blargs # as list infix operator to infix:<X></lang>
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
describing that is not the purpose of this task. Suffice to say that we assume here that the
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 Perl 6 (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 perl6>my @args = 1,2,3;
foo(|@args); # equivalent to foo(1,2,3)</lang>
 
Calling a function with named arguments:
 
<lang perl6>foo :a, :b(4), :!c, d => "stuff"
foo(:a, :b(4), :!c, d => "stuff")</lang>
 
...and so on. Operators may also be called with named arguments, but only
colon adverbials are allowed:
 
<lang perl6>1 + 1 :a :b(4) :!c :d("stuff") # calls infix:<+>(1,1,:a, :b(4), :!c, d => "stuff")</lang>
 
Using a function in statement context:
 
<lang perl6>foo(); bar(); baz(); # evaluate for side effects</lang>
 
Using a function in first class context within an expression:
 
<lang perl6>1 / find-a-func(1,2,3)(4,5,6) ** 2;</lang>
 
Obtaining the return value of a function:
 
<lang perl6>my $result = somefunc(1,2,3) + 2;</lang>
 
There is no difference between calling builtins and user-defined functions and operators (or
even control stuctures). This was a major design goal of Perl 6, and apart from a very few
low-level primitives, all of Perl 6 can be written in Perl 6.
 
There is no difference between calling subroutines and functions in Perl 6, other than that
calling a function in void context that has no side effects is likely to get you a "Useless use of..." warning.
And, of course, the fact that pure functions can participate in more optimizations such as constant folding.
 
By default, arguments are passed readonly, which allows the implementation to decide whether pass-by-reference or pass-by-value is more efficient on a case-by-case basis. Explicit lvalue, reference, or copy semantics may be requested on a parameter-by-parameter basis, and the entire argument list may be processed raw if that level of control is needed.
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Phix has three kinds of routines: procedure, function, and type. A procedure does not return a value, whereas a function does.
A type is a specialised kind of function that permits declarations of instances which are automatically validated whenever they are changed, further a type routine always returns either true or false.
* Phix does not allow implicit discard of function results. The explicit discard statement takes the form
 
<lang Phix>{} = myfunction()</lang>
<!--<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;">)
<!--</syntaxhighlight>-->
 
* This is in fact a simple contraction of standard multiple assigment (which can be nested as deeply as you like):
 
<lang Phix>{cities,populations} = columize(muncipalities)
<!--<syntaxhighlight lang="phix">-->
{{},populations} = columize(muncipalities) -- discard result[1]
<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>
{cities,{}} = columize(muncipalities) -- discard result[2]
<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>
{cities} = columize(muncipalities) -- ""</lang>
<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;">-- ""
<!--</syntaxhighlight>-->
* 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:
 
<lang Phix>function myfunction(integer a, string b="default")
<!--<syntaxhighlight lang="phix">-->
return {a,b}
<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>
end function
<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>
--? myfunction() -- illegal, compile-time error
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?myfunction(1) -- displays {1,"default"}
<span style="color: #000080;font-style:italic;">--? myfunction() -- illegal, compile-time error</span>
?myfunction(2,"that") -- displays {2,"that"}</lang>
<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"}
<!--</syntaxhighlight>-->
 
* 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:
 
<lang Phix>?myfunction(b:="then",a:=3) -- displays {3,"then"}
<!--<syntaxhighlight lang="phix">-->
--?myfunction(b:="though") -- compile-time error</lang>
<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
<!--</syntaxhighlight>-->
 
* The programmer is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first).
* Phix does not support first-class functions directly, butas insteadintegers, usesalong with an integerolder routine_id mechanism (and obviously integers are first-class):
 
<lang Phix>constant integer r_my_func = routine_id("myroutine")
<!--<syntaxhighlight lang="phix">-->
?call_func(r_my_func,{1}) -- displays {1,"default"}</lang>
<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: #0000FF;">?<span style="color: #7060A8;">call_func<span style="color: #0000FF;">(<span style="color: #000000;">r_myfunction<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;">-- displays {1,"default"}</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">call_func<span style="color: #0000FF;">(<span style="color: #000000;">myfunction<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;">-- ""
<!--</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>
Note however that for performance reasons some builtins do not have a proper routine_id; if you need one you must write a trivial one-line wrapper.<br>
Line 3,276 ⟶ 4,794:
* Partial application is usually achieved through a single variable-length "user_data" parameter within a call_func() expression.
* 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:
 
<lang Phix>s = append(s,item)</lang>
<!--<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;">)
<!--</syntaxhighlight>-->
 
* Implicit forward calls are supported, as are optional explicit forward declarations, which can occasionally cure compilation error messages.
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">/# Phixmonti does not distinguish between subroutines and functions.
Each word (as they are called), takes its arguments (if any) from the data stack. #/
def saludo
"Hola mundo" print nl
enddef
 
saludo /# 'saludo' is a user-defined word. #/
 
2 3 + print /# The '+' sign and 'print' are intrinsic words. The return value is deposited on the data stack #/ </syntaxhighlight>
 
=={{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):
<langsyntaxhighlight PicoLisplang="picolisp">(foo)
(bar 1 'arg 2 'mumble)</langsyntaxhighlight>
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):
<langsyntaxhighlight PicoLisplang="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</langsyntaxhighlight>
Any argument to a function may be evaluated or not, depending on the function. For example, 'setq' evaluates every second argument
<langsyntaxhighlight PicoLisplang="picolisp">(setq A (+ 3 4) B (* 3 4))</langsyntaxhighlight>
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}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">Procedure Saludo()
PrintN("Hola mundo!")
EndProcedure
 
Procedure.s Copialo(txt.s, siNo.b, final.s = "")
Define nuevaCadena.s, resul.s
For cont.b = 1 To siNo
nuevaCadena + txt
Next
Resul = Trim(nuevaCadena) + final
ProcedureReturn resul
EndProcedure
 
Procedure testNumeros(a.i, b.i, c.i = 0)
PrintN(Str(a) + #TAB$ + Str(b) + #TAB$ + Str(c))
EndProcedure
 
Procedure testCadenas(txt.s)
For cont.b = 1 To Len(txt)
Print(Mid(txt,cont,1))
Next cont
EndProcedure
 
OpenConsole()
Saludo()
PrintN(Copialo("Saludos ", 6))
PrintN(Copialo("Saludos ", 3, "!!"))
PrintN("")
testNumeros(1, 2, 3)
testNumeros(1, 2)
PrintN("")
testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")
 
Input()
CloseConsole()</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
=={{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).
<langsyntaxhighlight lang="python">def no_args():
pass
# call
Line 3,361 ⟶ 4,935:
 
## For partial function application see:
## http://rosettacode.org/wiki/Partial_function_application#Python</langsyntaxhighlight>
=={{header|QBasic}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">FUNCTION Copialo$ (txt$, siNo, final$)
DIM nuevaCadena$
FOR cont = 1 TO siNo
nuevaCadena$ = nuevaCadena$ + txt$
NEXT cont
Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) + final$
END FUNCTION
 
SUB Saludo
PRINT "Hola mundo!"
END SUB
 
SUB testCadenas (txt$)
FOR cont = 1 TO LEN(txt$)
PRINT MID$(txt$, cont, 1); "";
NEXT cont
END SUB
 
SUB testNumeros (a, b, c)
PRINT a, b, c
END SUB
 
CALL Saludo
PRINT Copialo$("Saludos ", 6, "")
PRINT Copialo$("Saludos ", 3, "!!")
PRINT
CALL testNumeros(1, 2, 3)
CALL testNumeros(1, 2, 0)
PRINT
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
=={{header|Quackery}}==
 
Words in Quackery take zero or more arguments from the (programmer accessible) data stack, and return zero or more results to the data stack.
 
In this dialogue in the Quackery shell, <code>/mod</code> takes two arguments and returns two results, <code>pack</code> takes three arguments (the topmost argument on the stack (<code>2</code>) specifies how many more arguments it is to take from the stack), <code>echo</code> takes one argument and returns no results, and <code>cr</code> takes no arguments and returns no results.
 
<pre>/O> 123 7 /mod
...
 
Stack: 17 4
 
/O> 2 pack
...
 
Stack: [ 17 4 ]
 
/O> echo cr
...
[ 17 4 ]
 
Stack empty.</pre>
 
Words can also take one or more items (nests, words or numbers) and arbitrary strings of text following the word as arguments. For example, <code>times</code> performs the item following it a specified number of times, and <code>say</code> echoes the string following it to the terminal.
 
<pre>/O> 4 times [ 3 times [ say "badger" sp ] cr ]
... 2 times [ say "mushroom" sp ] cr
...
badger badger badger
badger badger badger
badger badger badger
badger badger badger
mushroom mushroom
 
Stack empty.
</pre>
=={{header|R}}==
Translated from Python, when possible.
<langsyntaxhighlight lang="rsplus">### Calling a function that requires no arguments
no_args <- function() NULL
no_args()
Line 3,422 ⟶ 5,070:
 
### Is partial application possible and how
# Yes, see http://rosettacode.org/wiki/Partial_function_application#R</langsyntaxhighlight>
 
 
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,467 ⟶ 5,112:
(curry foo 1 2) ; later apply this on 3
(λ(x) (foo 1 2 x)) ; a direct way of doing the same
</syntaxhighlight>
</lang>
=={{header|Raku}}==
(formerly Perl 6)
===Theory===
Fundamentally, nearly everything you do in Raku is a function call if you look hard enough.
At the lowest level, a function call merely requires a reference to any
kind of invokable object, and a call to its <tt>postcircumfix:&lt;( )&gt;</tt> method.
However, there are various forms of sugar and indirection that you
can use to express these function calls differently. In particular,
operators are all just sugar for function calls.
 
Calling a function that requires no arguments:
 
<syntaxhighlight lang="raku" line>foo # as list operator
foo() # as function
foo.() # as function, explicit postfix form
$ref() # as object invocation
$ref.() # as object invocation, explicit postfix
&foo() # as object invocation
&foo.() # as object invocation, explicit postfix
::($name)() # as symbolic ref</syntaxhighlight>
 
Calling a function with exactly one argument:
 
<syntaxhighlight lang="raku" line>foo 1 # as list operator
foo(1) # as named function
foo.(1) # as named function, explicit postfix
$ref(1) # as object invocation (must be hard ref)
$ref.(1) # as object invocation, explicit postfix
1.$foo # as pseudo-method meaning $foo(1) (hard ref only)
1.$foo() # as pseudo-method meaning $foo(1) (hard ref only)
1.&foo # as pseudo-method meaning &foo(1) (is hard foo)
1.&foo() # as pseudo-method meaning &foo(1) (is hard foo)
1.foo # as method via dispatcher
1.foo() # as method via dispatcher
1."$name"() # as method via dispatcher, symbolic
+1 # as operator to prefix:<+> function</syntaxhighlight>
 
Method calls are included here because they do eventually dispatch to a true
function via a dispatcher. However, the dispatcher in question is not going
to dispatch to the same set of functions that a function call of that name
would invoke. That's why there's a dispatcher, after all. Methods are declared
with a different keyword, <tt>method</tt>, in Raku, but all that does is
install the actual function into a metaclass. Once it's there, it's merely
a function that expects its first argument to be the invocant object. Hence we
feel justified in including method call syntax as a form of indirect function call.
 
Operators like <tt>+</tt> also go through a dispatcher, but in this case it is
multiply dispatched to all lexically scoped candidates for the function. Hence
the candidate list is bound early, and the function itself can be bound early
if the type is known. Raku maintains a clear distinction between early-bound
linguistic constructs that force Perlish semantics, and late-bound OO dispatch
that puts the objects and/or classes in charge of semantics. (In any case, <tt>&foo</tt>,
though being a hard ref to the function named "foo", may actually be a ref to
a dispatcher to a list of candidates that, when called, makes all the candidates behave as a single unit.)
 
Calling a function with exactly two arguments:
 
<syntaxhighlight lang="raku" line>foo 1,2 # as list operator
foo(1,2) # as named function
foo.(1,2) # as named function, explicit postfix
$ref(1,2) # as object invocation (must be hard ref)
$ref.(1,2) # as object invocation, explicit postfix
1.$foo: 2 # as pseudo-method meaning $foo(1,2) (hard ref only)
1.$foo(2) # as pseudo-method meaning $foo(1,2) (hard ref only)
1.&foo: 2 # as pseudo-method meaning &foo(1,2) (is hard foo)
1.&foo(2) # as pseudo-method meaning &foo(1,2) (is hard foo)
1.foo: 2 # as method via dispatcher
1.foo(2) # as method via dispatcher
1."$name"(2) # as method via dispatcher, symbolic
1 + 2 # as operator to infix:<+> function</syntaxhighlight>
 
Optional arguments don't look any different from normal arguments.
The optionality is all on the binding end.
 
Calling a function with a variable number of arguments (varargs):
 
<syntaxhighlight lang="raku" line>foo @args # as list operator
foo(@args) # as named function
foo.(@args) # as named function, explicit postfix
$ref(@args) # as object invocation (must be hard ref)
$ref.(@args) # as object invocation, explicit postfix
1.$foo: @args # as pseudo-method meaning $foo(1,@args) (hard ref)
1.$foo(@args) # as pseudo-method meaning $foo(1,@args) (hard ref)
1.&foo: @args # as pseudo-method meaning &foo(1,@args)
1.&foo(@args) # as pseudo-method meaning &foo(1,@args)
1.foo: @args # as method via dispatcher
1.foo(@args) # as method via dispatcher
1."$name"(@args) # as method via dispatcher, symbolic
@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
on whether a signature accepts a list at that position in the argument list, but
describing that is not the purpose of this task. Suffice to say that we assume here that the
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:
 
<syntaxhighlight lang="raku" line>my @args = 1,2,3;
foo(|@args); # equivalent to foo(1,2,3)</syntaxhighlight>
 
Calling a function with named arguments:
 
<syntaxhighlight lang="raku" line>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
colon adverbials are allowed:
 
<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:
 
<syntaxhighlight lang="raku" line>foo(); bar(); baz(); # evaluate for side effects</syntaxhighlight>
 
Using a function in first class context within an expression:
 
<syntaxhighlight lang="raku" line>1 / find-a-func(1,2,3)(4,5,6) ** 2;</syntaxhighlight>
 
Obtaining the return value of a function:
 
<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
even control stuctures). This was a major design goal of Raku, and apart from a very few
low-level primitives, all of Raku can be written in Raku.
 
There is no difference between calling subroutines and functions in Raku, other than that
calling a function in void context that has no side effects is likely to get you a "Useless use of..." warning.
And, of course, the fact that pure functions can participate in more optimizations such as constant folding.
 
By default, arguments are passed readonly, which allows the implementation to decide whether pass-by-reference or pass-by-value is more efficient on a case-by-case basis. Explicit lvalue, reference, or copy semantics may be requested on a parameter-by-parameter basis, and the entire argument list may be processed raw if that level of control is needed.
===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.
<syntaxhighlight lang="raku" line>{
state $n;
 
multi f () { print ' f' ~ ++$n }
multi f ($a) { die if 1 != $a; print ' f' ~ ++$n }
multi f ($a,$b) { die if 3 != $a+$b; print ' f' ~ ++$n }
multi f (@a) { die if @a != [2,3,4]; print ' f' ~ ++$n }
multi f ($a,$b,$c) { die if 2 != $a || 4 != $c; print ' f' ~ ++$n }
sub g ($a,*@b) { die if @b != [2,3,4] || 1 != $a; print ' g' ~ ++$n }
 
my \i = -> { print ' i' ~ ++$n }
my \l = -> $a { die if 1 != $a; print ' l' ~ ++$n }
my \m = -> $a,$b { die if 1 != $a || 2 != $b; print ' m' ~ ++$n }
my \n = -> @a { die if @a != [2,3,4]; print ' n' ~ ++$n }
 
Int.^add_method( 'j', method ()
{ die if 1 != self; print ' j' ~ ++$n } );
Int.^add_method( 'k', method ($a)
{ die if 1 != self || 2 != $a; print ' k' ~ ++$n } );
Int.^add_method( 'h', method (@a)
{ die if @a != [2,3,4] || 1 != self; print ' h' ~ ++$n } );
 
my $ref = &f; # soft ref
my $f := &f; # hard ref
my $g := &g; # hard ref
my $f-sym = '&f'; # symbolic ref
my $g-sym = '&g'; # symbolic ref
my $j-sym = 'j'; # symbolic ref
my $k-sym = 'k'; # symbolic ref
my $h-sym = 'h'; # symbolic ref
 
# Calling a function with no arguments:
 
f; # 1 as list operator
f(); # 2 as function
i.(); # 3 as function, explicit postfix form # defined via pointy-block
$ref(); # 4 as object invocation
$ref.(); # 5 as object invocation, explicit postfix
&f(); # 6 as object invocation
&f.(); # 7 as object invocation, explicit postfix
::($f-sym)(); # 8 as symbolic ref
 
# Calling a function with exactly one argument:
 
f 1; # 9 as list operator
f(1); # 10 as named function
l.(1); # 11 as named function, explicit postfix # defined via pointy-block
$f(1); # 12 as object invocation (must be hard ref)
$ref.(1); # 13 as object invocation, explicit postfix
1.$f; # 14 as pseudo-method meaning $f(1) (hard ref only)
1.$f(); # 15 as pseudo-method meaning $f(1) (hard ref only)
1.&f; # 16 as pseudo-method meaning &f(1) (is hard f)
1.&f(); # 17 as pseudo-method meaning &f(1) (is hard f)
1.j; # 18 as method via dispatcher # requires custom method, via 'Int.^add_method'
1.j(); # 19 as method via dispatcher
1."$j-sym"(); # 20 as method via dispatcher, symbolic
 
# Calling a function with exactly two arguments:
 
f 1,2; # 21 as list operator
f(1,2); # 22 as named function
m.(1,2); # 23 as named function, explicit postfix # defined via pointy-block
$ref(1,2); # 24 as object invocation (must be hard ref)
$ref.(1,2); # 25 as object invocation, explicit postfix
1.$f: 2; # 26 as pseudo-method meaning $f(1,2) (hard ref only)
1.$f(2); # 27 as pseudo-method meaning $f(1,2) (hard ref only)
1.&f: 2; # 28 as pseudo-method meaning &f(1,2) (is hard f)
1.&f(2); # 29 as pseudo-method meaning &f(1,2) (is hard f)
1.k: 2; # 30 as method via dispatcher # requires custom method, via 'Int.^add_method'
1.k(2); # 31 as method via dispatcher
1."$k-sym"(2); # 32 as method via dispatcher, symbolic
 
# Calling a function with a variable number of arguments (varargs):
 
my @args = 2,3,4;
 
f @args; # 33 as list operator
f(@args); # 34 as named function
n.(@args); # 35 as named function, explicit postfix # defined via pointy-block
$ref(@args); # 36 as object invocation (must be hard ref)
$ref.(@args); # 37 as object invocation, explicit postfix
1.$g: @args; # 38 as pseudo-method meaning $f(1,@args) (hard ref)
1.$g(@args); # 39 as pseudo-method meaning $f(1,@args) (hard ref)
1.&g: @args; # 40 as pseudo-method meaning &f(1,@args)
1.&g(@args); # 41 as pseudo-method meaning &f(1,@args)
1.h: @args; # 42 as method via dispatcher # requires custom method, via 'Int.^add_method'
1.h(@args); # 43 as method via dispatcher
1."$h-sym"(@args); # 44 as method via dispatcher, symbolic
f(|@args); # 45 equivalent to f(1,2,3)
 
}</syntaxhighlight>
{{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>
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX programpgms to demonstratedemonstrates various methods/approaches of invoking/calling a REXX function.*/
/*┌────────────────────────────────────────────────────────────────────┐
│ Calling a function that REQUIRES no arguments. │
│ │
│ In the REXX language, there is no way to require the caller to not │
│ pass arguments, but the programmer can check if any arguments were │
│ (or weren't) passed. │
└────────────────────────────────────────────────────────────────────┘*/
yr=yearFunc()
say 'year=' yr
exit
 
/*╔════════════════════════════════════════════════════════════════════╗
yearFunc: procedure
if arg()\==0 then call sayErr "SomeFunc ║ Calling a function won'tthat acceptREQUIRES no arguments."
║ ║
return left(date('Sorted'),3)
║ In the REXX language, there is no way to require the caller to not ║
/*┌────────────────────────────────────────────────────────────────────┐
║ pass arguments, but the programmer can check if any arguments were ║
│ Calling a function with a fixed number of arguments. │
(or weren't) passed.
╚════════════════════════════════════════════════════════════════════╝*/
│ I take this to mean that the function requires a fixed number of │
│ arguments. As above, REXX doesn't enforce calling (or invoking) │
│ a (any) function with a certain number of arguments, but the │
│ programmer can check if the correct number of arguments have been │
│ specified (or not). │
└────────────────────────────────────────────────────────────────────┘*/
ggg=FourFunc(12,abc,6+q,zz%2,'da 5th disagreement')
say 'ggg squared=' ggg**2
exit
 
yr= yearFunc() /*the function name is caseless if it isn't */
FourFunc: procedure; parse arg a1,a2,a3; a4=arg(4) /*another way get a4*/
/*enclosed in quotes (') or apostrophes (").*/
say 'year=' yr
exit /*stick a fork in it, we're all done. */
 
yearFunc: procedure /*function ARG returns the # of args.*/
if arg()\==4 then do
errmsg= '***error***' /*an error message eyecatcher string. */
call sayErr "FourFunc function requires 4 arguments,"
if arg() \== 0 then say errmsg call sayErr "butthe insteadYEARFUNC itfunction found"won't arg()accept 'arguments.'"
return left( date('Sorted'), exit 133)</syntaxhighlight>
end
return a1+a2+a3+a4
/*┌────────────────────────────────────────────────────────────────────┐
│ Calling a function with optional arguments. │
│ │
│ Note that not passing an argument isn't the same as passing a null │
│ argument (a REXX variable whose value is length zero). │
└────────────────────────────────────────────────────────────────────┘*/
x=12; w=x/2; y=x**2; z=x//7 /* z is x modulo seven.*/
say 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass 5 args, 4th is null*/
exit
 
SumIt: procedure; sum=0
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
do j=1 for arg()
║ Calling a function with a fixed number of arguments. ║
if arg(j,'E') then sum=sum+arg(j) /*the Jth arg may have been omitted*/
║ ║
end
║ I take this to mean that the function requires a fixed number of ║
║ arguments. As above, REXX doesn't enforce calling (or invoking) ║
║ a (any) function with a certain number of arguments, but the ║
║ programmer can check if the correct number of arguments have been ║
║ specified (or not). ║
║ In some languages, these are known as "generic" functions. ║
╚════════════════════════════════════════════════════════════════════╝*/
 
ggg= FourFunc(12, abc, 6+q, zz%2, 'da 5th disagreement')
say 'ggg squared=' ggg**2
exit /*stick a fork in it, we're all done. */
 
FourFunc: procedure; parse arg a1,a2,a3 /*obtain the first three arguments. */
a4= arg(4) /*another way to obtain the 4th arg. */
errmsg= '***error***' /*an error message eyecatcher string. */
if arg() \== 4 then do
say err "FourFunc function requires 4 arguments,"
say err "but instead it found" arg() 'arguments.'
exit 13 /*exit function with a RC of 13*/
end
 
return a1 + a2 + a3 + a4</syntaxhighlight>
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function with optional arguments. ║
║ ║
║ Note that not passing an argument isn't the same as passing a null ║
║ argument (a REXX variable whose value is length zero). ║
╚════════════════════════════════════════════════════════════════════╝*/
 
x= 12; w= x/2; y= x**2; z= x//7 /* z is x modulo seven. */
say 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass five args, the 4th arg is "null"*/
exit /*stick a fork in it, we're all done. */
 
SumIt: procedure
$= 0 /*initialize the sum to zero. */
do j=1 for arg() /*obtain the sum of a number of args. */
if arg(j,'E') then $= $ + arg(j) /*the Jth arg may have been omitted. */
end /*j*/
 
return $</syntaxhighlight>
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function with a variable number of arguments. ║
║ ║
║ This situation isn't any different then the previous example. ║
║ It's up to the programmer to code how to utilize the arguments. ║
╚════════════════════════════════════════════════════════════════════╝*/
 
/*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function with named arguments. ║
║ ║
║ REXX allows almost anything to be passed, so the following is one ║
║ way this can be accomplished. ║
╚════════════════════════════════════════════════════════════════════╝*/
 
what= parserFunc('name=Luna', "gravity=.1654", 'moon=yes')
return sum
say 'name=' common.name
/*┌────────────────────────────────────────────────────────────────────┐
gr= common.gr
│ Calling a function with a variable number of arguments. │
│ │
│ This situation isn't any different then the previous example. │
│ It's up to the programmer to code how to utilize the arguments. │
└────────────────────────────────────────────────────────────────────┘*/
/*┌────────────────────────────────────────────────────────────────────┐
│ Calling a function with named arguments. │
│ │
│ REXX allows almost anything to be passed, so the following is one │
│ way this can be accomplished. │
└────────────────────────────────────────────────────────────────────┘*/
what=parserFunc('name=Luna',"gravity=.1654",'moon=yes')
say 'name=' common.name
gr=common.gr
say 'gravity=' gr
exit /*stick a fork in it, we're all done. */
exit
 
parseFunc: procedure expose common.
do j=1 for arg()
parse var arg(j) name '=' val
upper name /*uppercase it.*/
upper name
call value 'COMMON.'name,val
end
return arg()</syntaxhighlight>
 
/*┌────────────────────────────────────────────────────────────────────┐
 
│ Calling a function in statement context. │
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
│ │
║ Calling a function in statement context. ║
│ REXX allows functions to be called (invoked) two ways, the first │
║ ║
│ example (above) is calling a function in statement context. │
║ REXX allows functions to be called (invoked) two ways, the first ║
└────────────────────────────────────────────────────────────────────┘*/
║ example (above) is calling a function in statement context. ║
/*┌────────────────────────────────────────────────────────────────────┐
╚════════════════════════════════════════════════════════════════════╝*/
│ Calling a function in within an expression. │
 
│ │
/*╔════════════════════════════════════════════════════════════════════╗
│ This is a variant of the first example. │
║ Calling a function in within an expression. ║
└────────────────────────────────────────────────────────────────────┘*/
║ ║
yr=yearFunc()+20
║ This is a variant of the first example. ║
╚════════════════════════════════════════════════════════════════════╝*/
 
yr= yearFunc() + 20
say 'two decades from now, the year will be:' yr
exit /*stick a fork in it, we're all done. */</syntaxhighlight>
exit
 
/*┌────────────────────────────────────────────────────────────────────┐
 
│ Obtaining the return value of a function. │
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
│ │
There are two ways to get ║ Obtaining the (return) value of a function.
║ ║
└────────────────────────────────────────────────────────────────────┘*/
║ There are 2 ways to get the (return) value (RESULT) of a function. ║
currYear=yearFunc()
╚════════════════════════════════════════════════════════════════════╝*/
say 'the current year is' currYear
 
currYear= yearFunc()
say 'the current year is' currYear
 
call yearFunc
say 'the current year is' result /*result can be RESULT, it is caseless.*/</syntaxhighlight>
 
/*┌────────────────────────────────────────────────────────────────────┐
 
│ Distinguishing built-in functions and user-defined functions. │
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
│ │
║ Distinguishing built-in functions and user-defined functions. ║
│ One objective of the REXX language is to allow the user to use any │
║ ║
│ function (or subroutine) name whether or not there is a built-in │
║ One objective of the REXX language is to allow the user to use any ║
│ function with the same name (there isn't a penality for this). │
║ function (or subroutine) name whether or not there is a built-in ║
└────────────────────────────────────────────────────────────────────┘*/
qqq=date() function with the /*numbersame ofname real dates(there thatisn't Boba waspenality onfor this). */
╚════════════════════════════════════════════════════════════════════╝*/
say "Bob's been out" qqq 'times.'
 
www='DATE'('USA') /*returns date in format mm/dd/yyy */
exit /*anydate: function as in quotesgoing is external.out with someone. */
qqq= date() /*number of real dates that Bob was on.*/
/*hopefully, it accurately counts dates*/
say "Bob's been out" qqq 'times.'
www= 'DATE'("USA") /*returns date in format mm/dd/yyyy */
/*any function in quotes is external. */
exit /*stick a fork in it, we're all done. */
 
date: return 4 /*Bob only "went out" 4 times, no need */
/* to actually count, he quit after 4. */</syntaxhighlight>
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Distinguishing subroutines and functions. ║
║ ║
║ There is no programmatic difference between subroutines and ║
║ functions if the subroutine returns a value (which effectively ║
║ makes it a function). REXX allows you to call a function as if ║
║ it were a subroutine. ║
╚════════════════════════════════════════════════════════════════════╝*/
 
/*╔════════════════════════════════════════════════════════════════════╗
║ In REXX, all arguments are passed by value, never by name, but it ║
║ is possible to accomplish this if the variable's name is passed ║
║ and the subroutine/function could use the built-in-function VALUE ║
║ to retrieve the variable's value. ║
╚════════════════════════════════════════════════════════════════════╝*/
 
/*╔════════════════════════════════════════════════════════════════════╗
date: return 4
║ In the REXX language, partial application is possible, depending ║
/*┌────────────────────────────────────────────────────────────────────┐
Distinguishing subroutines and functions. how partial application is defined; I prefer the 1st definition
(as per the "discussion" for "Partial Function Application" task:
║ 1. The "syntactic sugar" that allows one to write some examples ║
│ There is no programatic difference between subroutines and │
║ are: map (f 1 9) [1..9] ║
│ functions if the subroutine returns a value (which effectively │
║ or: map (f(1,_,9)) [1, ..., 9] ║
│ makes it a function). REXX allows you to call a function as if │
╚════════════════════════════════════════════════════════════════════╝*/</syntaxhighlight>
│ it were a subroutine. │
└────────────────────────────────────────────────────────────────────┘*/
/*┌────────────────────────────────────────────────────────────────────┐
│ In REXX, all arguments are passed by value, never by name, but it │
│ is possible to accomplish this if the variable's name is passed │
│ and the subroutine/function could use the built-in-function VALUE │
│ to retrieve the variable's value. │
└────────────────────────────────────────────────────────────────────┘*/
/*┌────────────────────────────────────────────────────────────────────┐
│ In the REXX language, partial application is possible, depending │
│ how partial application is defined; I prefer the 1st definition (as│
│ (as per the "discussion" for "Partial Function Application" task: │
│ 1. The "syntactic sugar" that allows one to write (some examples│
│ are: map (f 7 9) [1..9] │
│ or: map(f(7,_,9),{1,...,9}) │
└────────────────────────────────────────────────────────────────────┘*/</lang>
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 29.07.2013 Walter Pachl trying to address the task concisely
***********************************************************************
Line 3,686 ⟶ 5,588:
If sigl=39 Then
Say 'fb cannot be invoked as function (it does not return a value'
Exit</langsyntaxhighlight>
{{out}}
<pre>
Line 3,724 ⟶ 5,626:
rc=44 (Function or message did not return data)
fb cannot be invoked as function (it does not return a value)</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
hello()
func hello
see "Hello from function" + nl
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="ring">
first() second()
func first see "message from the first function" + nl
func second see "message from the second function" + nl
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="ring">
sum(3,5) sum(1000,2000)
func sum x,y see x+y+nl
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="ring">
# this program will print the hello world message first then execute the main function
See "Hello World!" + nl
func main
see "Message from the main function" + nl
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Ruby does not have functions, but Ruby classes have "methods" which are equivalent.
Line 3,754 ⟶ 5,654:
 
*Calling a function that requires no arguments
:<langsyntaxhighlight lang="ruby">def foo() p "foo" end
 
foo #=> "foo"
foo() #=> "foo"</langsyntaxhighlight>
 
*Calling a function with a fixed number of arguments
:<langsyntaxhighlight lang="ruby">def foo arg; p arg end # one argument
 
foo(1) #=> 1
foo "1" #=> "1"
foo [0,1,2] #=> [0, 1, 2] (one Array)</langsyntaxhighlight>
 
*Calling a function with optional arguments
:<langsyntaxhighlight lang="ruby">def foo(x=0, y=x, flag=true) p [x,y,flag] end
 
foo #=> [0, 0, true]
foo(1) #=> [1, 1, true]
foo(1,2) #=> [1, 2, true]
foo 1,2,false #=> [1, 2, false]</langsyntaxhighlight>
 
*Calling a function with a variable number of arguments
:<langsyntaxhighlight lang="ruby">def foo(*args) p args end
 
foo #=> []
foo(1,2,3,4,5) #=> [1, 2, 3, 4, 5]</langsyntaxhighlight>
 
*Calling a function with named arguments
:<langsyntaxhighlight lang="ruby">def foo(id:0, name:"", age:0) p [id, name, age] end
 
foo(age:22, name:"Tom") #=> [0, "Tom", 22]</langsyntaxhighlight>
 
*Using a function in statement context
Line 3,793 ⟶ 5,693:
 
*Obtaining the return value of a function
:<langsyntaxhighlight lang="ruby">def foo(a,b) a + b end
 
bar = foo 10,20
Line 3,804 ⟶ 5,704:
x,y = sum_and_product(3,5)
p x #=> 8
p y #=> 15</langsyntaxhighlight>
 
*Distinguishing built-in functions and user-defined functions
Line 3,814 ⟶ 5,714:
::These methods are called without a receiver and thus can be called in functional form.
 
::<langsyntaxhighlight lang="ruby">puts "OK!" # Kernel#puts
raise "Error input" # Kernel#raise
Integer("123") # Kernel#Integer
Line 3,825 ⟶ 5,725:
private # Module#private
require # Kernel#require
loop { } # Kernel#loop</langsyntaxhighlight>
 
*Stating whether arguments are passed by value or by reference
Line 3,839 ⟶ 5,739:
::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>.
::<langsyntaxhighlight lang="ruby">class Array
def sum(init=0, &blk)
if blk
Line 3,852 ⟶ 5,752:
p ary.sum #=> 15
p ary.sum(''){|n| (-n).to_s} #=> "-1-2-3-4-5"
p (ary.sum do |n| n * n end) #=> 55</langsyntaxhighlight>
 
:Splat operator:
::You can turn an Array into an argument list with * (or splat) operator.
::<langsyntaxhighlight lang="ruby">def foo(a,b,c) p [a,b,c] end
 
args = [1,2,3]
foo *args #=> [1, 2, 3]
args = [1,2]
foo(0,*args) #=> [0, 1, 2]</langsyntaxhighlight>
 
:Syntax sugar:
::In Ruby, many operators are actually method calls.
::<langsyntaxhighlight lang="ruby"># return value substance
i = 3
p 1 + i #=> 4 1.+(i)
Line 3,877 ⟶ 5,777:
p a & [4,2] #=> [2] a.&([4,2])
p "abcde"[1..3] #=> "bcd" "abcde".[](1..3)
p "%2d %4s" % [1,"xyz"] #=> " 1 xyz" "%2d %4s".%([1,"xyz"])</langsyntaxhighlight>
::Method call which was displayed in the comment is usable actually.
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn main() {
// Rust has a lot of neat things you can do with functions: let's go over the basics first
fn no_args() {}
Line 3,970 ⟶ 5,870:
 
 
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods
def myFunction0() = ???
myFunction0() // function invoked with empty parameter list
Line 4,038 ⟶ 5,937:
 
// No distinction between built-in functions and user-defined functions
// No distinction between subroutines and functions</langsyntaxhighlight>
 
=={{header|Seed7}}==
* Seed7 provides two kinds of subroutines: ''proc'', which has no return value, and ''func'', which has a return value. The return value of a ''func'' must be used by the caller (e.g. assigned to a variable). If you don't want do deal with the return value, use a ''proc'' instead.
Line 4,047 ⟶ 5,945:
* All parameters are positional.
 
* There are no differences between between calling built-in vs. user defined functions.<langsyntaxhighlight lang="seed7">env := environment; # Call a function that requires 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.</langsyntaxhighlight>
 
* There are no optional arguments, but a similar effect can be achieved with overloading.<langsyntaxhighlight 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.</langsyntaxhighlight>
 
* 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:<langsyntaxhighlight lang="seed7">const func integer: sum (in array integer: intElems) is func
result
var integer: sum is 0;
Line 4,066 ⟶ 5,964:
 
s := sum([] (1, 2, 3)); # Use an aggregate to generate an array.
t := sum([] (2, 3, 5, 7));</langsyntaxhighlight>
 
* Concatenation operators can be used to concatenate arguments. This solution is used to provide the write function:<langsyntaxhighlight lang="seed7">write("Nr: " <& num); # Use operators to concatenate arguments.</langsyntaxhighlight>
 
* The procedure ignore can be used to ignore a return value.<langsyntaxhighlight lang="seed7">ignore(getln(IN)); # Using a function in statement context (ignore the result).</langsyntaxhighlight>
 
* 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:<langsyntaxhighlight lang="seed7">seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x));</langsyntaxhighlight>
=={{header|SenseTalk}}==
* 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:
put the zeroArgsFn
 
function zeroArgsFn
put "This function was run with zero arguments."
return "Return value from zero argument function"
end zeroArgsFn</syntaxhighlight>
 
* 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:
put the TwoArgFn of "variable", (3, 4)
 
// The parameter list is flexible, allowing any amount of variable to be passed in.
// These can be accessed with the keyword `the parameterList`
// The specified parameters only limits to named parameters
get TwoArgFn("variable", (3, 4), "hello")
get the TwoArgFn of "variable", (3, 4), "hello"
 
function TwoArgFn arg1, arg2
put "2 argument function: arg1 = " & arg1 & "; arg2 = " & arg2
put "Parameters = " & the parameterList
end TwoArgFn</syntaxhighlight>
 
* A parameter is set to "" if nothing is specified
<syntaxhighlight lang="sensetalk">get ThreeArgFn("variable", (3, 4))
 
function ThreeArgFn arg1, arg2, arg3
put "3 argument function: arg1 = " & arg1 & "; arg2 = " & arg2 & "; arg3 = " & arg3
end ThreeArgFn</syntaxhighlight>
 
* 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
 
function OneArgFn arg1
if arg1 is ""
set arg1 to 5
end if
put "One argument function; arg1 = " & arg1
end OneArgFn</syntaxhighlight>
 
* All variables are, by default, passed by value
* If the argument prefixed by 'container', the variable is passed by reference
<syntaxhighlight lang="sensetalk">put 3 into a
get AddOne(a)
put "Value of a = " & a
// Value of a = 3
 
put 5 into b
get AddOne(container b)
put "Value of b = " & b
// Value of b = 6
 
function AddOne n
add 1 to n
end AddOne</syntaxhighlight>
 
SenseTalk also distinguishes between functions and subroutines, which it calls handlers:
<syntaxhighlight lang="sensetalk">CustomHandler 1, 2, 3
// Prints: 1 - 2 - 3
 
to handle CustomHandler arg1, arg2, arg3
put arg1 && "-" && arg2 && "-" && arg3
end CustomHandler</syntaxhighlight>
 
Subroutines can be called as a command, without storing the output
<syntaxhighlight lang="sensetalk">
MyCommand 1, "variable", (4, 5, 6)
 
to MyCommand args
...
end MyCommand
</syntaxhighlight>
 
Functions/subroutines can also be defined with the to, on or function keywords:
<syntaxhighlight lang="sensetalk">to MyFn args
...
end MyFn
 
function MyFn args
...
end args
 
on MyFn args
...
end args
</syntaxhighlight>
=={{header|Sidef}}==
All functions in Sidef are first-class closures
<langsyntaxhighlight lang="ruby">foo(); # without arguments
foo(1, 2); # with two arguments
foo(args...); # with a variable number of arguments
Line 4,085 ⟶ 6,075:
 
var arr = [1,2,3];
foo(arr); # the arguments are passed by object-reference</langsyntaxhighlight>
 
Partial application is possible by using a curry function:
 
<langsyntaxhighlight lang="ruby">func curry(f, *args1) {
func (*args2) {
f(args1..., args2...);
Line 4,100 ⟶ 6,090:
 
var adder = curry(add, 1);
say adder(3); #=>4</langsyntaxhighlight>
 
=={{header|Slope}}==
 
Define and call a procedure:
<syntaxhighlight lang="slope">(define hello-world (lambda () (display "Hello, world!\n"))
(hello-world)</syntaxhighlight>
 
Call an anonymous procedure/lambda:
<syntaxhighlight lang="slope">((lambda () (display "Hello, world!\n")))</syntaxhighlight>
 
Define and call a procedure with arguments:
<syntaxhighlight lang="slope">(define hello (lambda (name) (display "Hello, " name "!\n")))
(hello "Rosetta Code")</syntaxhighlight>
 
Define and call an anonymous procedure with arguments:
<syntaxhighlight lang="slope">((lambda (name) (display "Hello, " name "!\n")) "Rosetta Code")</syntaxhighlight>
 
Defining a procedure that takes option arguments and defining one
that takes a variable number of arguments works the same. `...`
as a paramater represents a list of all arguments passed in from that
paramater forward. Here is an example usage for variable arguments:
<syntaxhighlight lang="slope">((lambda (op ...)
(if (null? ...)
(! "At least one argument is required")
(apply op ...)))
* 1 2 3 4)</syntaxhighlight>
 
Here is an example with an optional value:
<syntaxhighlight lang="slope">((lambda (first ...)
(define last (if (null? ...) "" (append " " (car ...))))
(display "Hello " first last "\n")) "John" "Kimball")</syntaxhighlight>
 
Partial application varies by procedure. Some built-ins use partial application
(such as `or`). Macros created with `macro` do not evaluate any arguments and the
macro definition is responsible for evaluating what it needs to. But macros likely
fall into a different category than the scope of this task.
 
=={{header|SmallBASIC}}==
<syntaxhighlight lang="basic">
func F1()
return 1
end
 
func F2(a)
return a + 1
end
 
func F3(a, b)
return a + b
end
 
func F4(byref a)
a = 5
return a + 1
end
 
sub S1(a, b)
print a, b
end
 
sub S2(byref a)
a = 5
end
 
var1 = 1
var2 = 2
 
' Functions return a result and return-value must be assigned to a variable
result = F1()
result = F2(var1)
result = F3(var1, var2)
' Parameters are passed by reference if byref is used in function definition
result = F4(var1) ' result = 6 and var1 = 5
 
' Subroutines can't return a result
S1(var1, var2)
' Parameters are passed by reference if byref is used in sub definition.
' This can be used to return a result indirectly
S2(var1) ' var1 = 5
 
' Functions and subroutines can take expressions as parameter
result = F2(1 + 2)
</syntaxhighlight>
 
 
=={{header|Smalltalk}}==
Where f is a closure and arguments is an array of values for f to operate on.
<syntaxhighlight lang ="smalltalk">f valueWithArguments: arguments.</langsyntaxhighlight>
 
=={{header|SSEM}}==
Assuming the subroutine has been set up in accordance with the Wheeler jump technique as described in the SSEM [[Function definition]] entry, calling it requires simply loading the return address into the accumulator and jumping out to the subroutine. Parameters must be passed using "global variables", i.e. storage locations; results may be passed the same way, although it is also possible to pass a return value in the accumulator.
 
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.
<langsyntaxhighlight lang="ssem">00110000000000100000000000000000 10. -12 to c
10110000000000000000000000000000 11. 13 to CI
11001111111111111111111111111111 12. -13
11001000000000000000000000000000 13. 19</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">// call a function with no args
noArgs()
 
Line 4,150 ⟶ 6,222:
 
// getting a bunch of return values, discarding second returned value
let (foo, _, baz) = returnSomeValues()</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">aCallToACommandWithNoArguments
aCallToACommandWithOne argument
aCallToACommandWith arbitrarily many arguments
Line 4,159 ⟶ 6,230:
aCallToACommandWith -oneNamed argument -andAnother namedArgument
aCallToACommandWith theNameOfAnotherCommand
aCallToOneCommand [withTheResultOfAnother]</langsyntaxhighlight>
Tcl does differentiate between functions and other types of commands in expressions:
<langsyntaxhighlight lang="tcl">expr {func() + [cmd]}
expr {func(1,2,3} + [cmd a b c]}</langsyntaxhighlight>
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).
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">FUNCTION Copialo$ (txt$, siNo, final$)
FOR cont = 1 TO ROUND(siNo)
LET nuevaCadena$ = nuevaCadena$ & txt$
NEXT cont
 
LET Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) & final$
END FUNCTION
 
SUB Saludo
PRINT "Hola mundo!"
END SUB
 
SUB testCadenas (txt$)
FOR cont = 1 TO ROUND(LEN(txt$))
PRINT (txt$)[cont:cont+1-1]; "";
NEXT cont
END SUB
 
SUB testNumeros (a, b, c)
PRINT a, b, c
END SUB
 
CALL Saludo
PRINT Copialo$("Saludos ", 6, "")
PRINT Copialo$("Saludos ", 3, "! !")
PRINT
CALL testNumeros(1, 2, 3)
CALL testNumeros(1, 2, 0)
PRINT
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")
END</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
=={{header|UNIX Shell}}==
 
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:
 
<langsyntaxhighlight lang="sh">sayhello # Call a function in statement context with no arguments
multiply 3 4 # Call a function in statement context with two arguments</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="vb">'definitions/declarations
 
'Calling a function that requires no arguments
Line 4,305 ⟶ 6,411:
End Sub
</langsyntaxhighlight>{{out}}
<pre>no arguments ok
no arguments ok
Line 4,322 ⟶ 6,428:
deprecated use of parentheses</pre>
=={{header|WDTE}}==
<langsyntaxhighlight lang="wdte">let noargs => + 2 5;
noargs -- print;
 
Line 4,341 ⟶ 6,447:
# evaluates `+ 3` and then passes 7 to the resulting partially applied
# function.
(+ 3) 7 -- print;</langsyntaxhighlight>
=={{header|WebAssembly}}==
 
<syntaxhighlight lang="webassembly">(func $main (export "_start")
 
(local $result i32)
 
;;Call a function with no arguments
call $noargfunc
 
;;Multiply two numbers and store the result, flat syntax
i32.const 12
i32.const 3
call $multipy
set_local $result
 
;;Multiply two numbers and store the result, indented syntax
(set_local $result
(call $multipy
(i32.const 12)
(i32.const 3)
)
)
 
;;Add two numbers in linear memory (similar to using pointers)
(i32.store (i32.const 0) (i32.const 5))
(i32.store (i32.const 4) (i32.const 7))
 
(call $addinmemory
(i32.const 0)
(i32.const 4)
(i32.const 8)
)
)</syntaxhighlight>
=={{header|Wren}}==
Wren distinguishes between functions and methods.
 
The former are first-class standalone objects which cannot be overloaded whereas the latter are always members of a class and can be overloaded by ''arity'' (i.e. the number of arguments they require). As Wren is dynamically typed and doesn't support type annotations, methods cannot be overloaded by parameter type. Methods can either be instance or static members of their class.
 
As well as 'ordinary' methods which always have a (possibly empty) parameter list, Wren also has the following types of methods:
 
1. 'constructors' which always have a parameter list and are really a pair of methods - a static method which creates a new instance of the class and then invokes an initializer on that instance.
 
2. 'getters' which leave off the parameter list.
 
3. 'setters' which have '=' after the name followed by a parameter list with just a single parameter.
 
4. 'operators' which, if they're infix operators, always have a parameter list with a single parameter. However, if they're prefix operators, they have no parameter list.
 
Wren does not support optional arguments, a variable number of arguments or named arguments though these can be respectively simulated by overloading, passing lists or passing maps.
 
Arguments are always passed by value though, if they're mutable reference types, it's the reference which gets copied so the function or method can mutate the object itself.
 
There are no built-in functions but all built-in classes have methods. Unless you know what they are, there is no way to distinguish between them and methods of user-defined classes.
 
The only way to distinguish between sub-routines and functions it to check whether they return a concrete value. The former always return null by default.
 
Partial function application is not supported ''per se'' but can be simulated as in the task of that name.
 
Here are some examples:
 
<syntaxhighlight lang="wren">var f1 = Fn.new { System.print("Function 'f1' with no arguments called.") }
var f2 = Fn.new { |a, b|
System.print("Function 'f2' with 2 arguments called and passed %(a) & %(b).")
}
var f3 = Fn.new { 42 } // function which returns a concrete value
 
f1.call() // statement context
f2.call(2, 3) // ditto
var v1 = 8 + f3.call() // calling function within an expression
var v2 = f3.call() // obtaining return value
System.print([v1, v2]) // print last two results as a list
 
class MyClass {
static m() { System.print("Static method 'm' called.") }
 
construct new(x) { _x = x } // stores 'x' in a field
 
x { _x } // gets the field
x=(y) { _x = y } // sets the field to 'y'
 
- { MyClass.new(-_x) } // prefix operator
+(o) { MyClass.new(_x + o.x) } // infix operator
 
toString { _x.toString } // instance method
}
 
MyClass.m() // call static method 'm'
var mc1 = MyClass.new(40) // construct 'mc1'
var mc2 = MyClass.new(8) // construct 'mc2'
System.print(mc1.x) // print mc1's field using getter
mc1.x = 42 // change mc1's field using setter
System.print(-mc1.x) // invoke prefix operator -
System.print(mc1 + mc2) // invoke infix operator +</syntaxhighlight>
 
{{out}}
<pre>
Function 'f1' with no arguments called.
Function 'f2' with 2 arguments called and passed 2 & 3.
[50, 42]
Static method 'm' called.
40
-42
50
</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">; call a function (procedure) with no arguments:
(foo)
 
Line 4,362 ⟶ 6,572:
; or it can simply be discarded
(foo bar)
; nothing is done with the return value</langsyntaxhighlight>
 
=={{header|XSLT}}==
 
<langsyntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
Line 4,643 ⟶ 6,852:
</xsl:template>
</xsl:stylesheet>
</syntaxhighlight>
</lang>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
sub test(a, b, c) : print a, b, c : end sub
 
Line 4,664 ⟶ 6,872:
 
test$("1, 2, 3, 4, text, 6, 7, 8, \"include text\"")
print</langsyntaxhighlight>
=={{header|Z80 Assembly}}==
Like most assembly languages, the concept of functions are too "high-level" for most of the task to apply. However, subroutines do exist and they are used like a function in a high-level language would be.
 
* Functions that require no arguments are the simplest. They are simply <code>CALL</code>ed without any special input.
 
* 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.
;usage: B = &0X, C = &0Y, => A = &XY
LD A,B
AND %00001111
RLCA
RLCA
RLCA
RLCA
OR C
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.
 
 
* Z80 Assembly does not support named arguments directly, but this can be achieved with assembly macros and labels.
 
 
* 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.
ADD a,b
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.
 
* Whether an argument is passed by value or by reference is again up to the programmer. By default, Z80 Assembly is pass-by-value, since it's much easier to operate on registers than directly on memory. The function would have to explicitly store the updated values back into memory for them to be altered. However, some Z80 instructions do directly alter memory, such as <code>RLD</code>,<code>RRD</code>,<code>LDIR</code>,etc.
=={{header|zkl}}==
The syntax and semantics of function calls is the always the same: name/object(parameters). All calls are varargs, it is up to the callee to do default/optional parameter handling (but that is hidden from the programmer). No named parameters. Pass by reference or value, depending.
 
Using f has a function, method or object:
<langsyntaxhighlight lang="zkl">f(); f(1,2,3,4);
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)
Line 4,679 ⟶ 6,920:
s:=f()
fcn{}.isType(self.fcn) //True
fcn{}.len.isType(self.fcn) //False, len is a Method</langsyntaxhighlight>
Partial application is done with the .fp* methods or the 'wrap keyword
<langsyntaxhighlight lang="zkl">
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
Line 4,691 ⟶ 6,932:
 
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))</langsyntaxhighlight>
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module CallingProcs;
type
Line 4,750 ⟶ 6,990:
writeln(total);
end CallingProcs.
</syntaxhighlight>
</lang>
 
=={{header|ZX Spectrum Basic}}==
 
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.
 
<langsyntaxhighlight 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
30 PRINT FN b(): REM Here we call a function that has no arguments
Line 4,767 ⟶ 7,006:
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
120 RANDOMIZE: REM statements are not functions and cannot be used in first class context.</langsyntaxhighlight>
 
{{omit from|GUISS}}
885

edits