Call a function: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
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()
Line 44:
opt_args() // 1
opt_args(3.141) // 3.141</syntaxhighlight>
 
=={{header|360 Assembly}}==
Due to assembler, argument are passed by reference.<br>
With:
<syntaxhighlight lang="360asm">X DS F
Y DS F
Z DS F</syntaxhighlight>
If you do not want to use the CALL macro instruction and for a link-edited object-module:
<syntaxhighlight lang="360asm"> L R15,=V(MULTPLIC)
LA R1,PARMLIST address of the paramter list
BALR R14,R15 branch and link
Line 60 ⟶ 59:
DC A(Y)</syntaxhighlight>
If you call a link-edited object-module:
<syntaxhighlight lang="360asm"> CALL MULTPLIC,(X,Y) call MULTPLIC(X,Y)
ST R0,Z Z=MULTPLIC(X,Y)</syntaxhighlight>
If you call an load-module at execution time:
<syntaxhighlight 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)</syntaxhighlight>
 
=={{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
Line 87 ⟶ 85:
 
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|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|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
Line 117 ⟶ 105:
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"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program callfonct.s */
Line 235 ⟶ 228:
Resultat : -90
</pre>
 
=={{header|ActionScript}}==
 
<syntaxhighlight 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</syntaxhighlight>
 
=={{header|Ada}}==
 
Line 250 ⟶ 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;</syntaxhighlight>
 
* Ada supports functions with optional parameters:<syntaxhighlight lang=Ada"ada">function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional
...
A : Integer := F(12);
Line 260 ⟶ 251:
* 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:<syntaxhighlight lang=Ada"ada">type Integer_Array is array (Positive range <>) of Integer;
function Sum(A: Integer_Array) return Integer is
S: Integer := 0;
Line 273 ⟶ 264:
B := Sum((1,2,3,4)); -- B = 10</syntaxhighlight>
 
* One can realize first-class functions by defining an access to a function as a parameter:<syntaxhighlight lang=Ada"ada">function H (Int: Integer;
Fun: not null access function (X: Integer; Y: Integer)
return Integer);
Line 283 ⟶ 274:
-- taking two Integers and returning an Integer.</syntaxhighlight>
 
* The caller is free to use either positional parameters or named parameters, or a mixture of both (with positional parameters first) <syntaxhighlight lang=Ada"ada">Positional := H(A, F'Access);
Named := H(Int => A, Fun => F'Access);
Mixed := H(A, Fun=>F'Access); </syntaxhighlight>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68"># Note functions and subroutines are called procedures (or PROCs) in Algol 68 #
# A function called without arguments: #
f;
Line 332 ⟶ 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}}==
<syntaxhighlight lang="algolw">% Note, in Algol W, functions are called procedures %
% calling a function with no parameters: %
f;
Line 372 ⟶ 361:
 
% Partial application is not possible in Algol W %</syntaxhighlight>
 
=={{header|AntLang}}==
AntLang provides two ways to apply a function.
One way is infix application.
<syntaxhighlight lang=AntLang"antlang">2*2+9</syntaxhighlight>
Infix application is right associative, so x f y g z means x f (y g z) and not (x f y) g z.
You can break this rule using parenthesis.
The other way is prefix application.
<syntaxhighlight lang=AntLang"antlang">*[2;+[2;9]]
echo["Hello!"]
time[]</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 561 ⟶ 548:
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">printHello: $[][
print "Hello World!"
]
Line 612 ⟶ 598:
yep, it worked
3</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AHK"ahk">; Call a function without arguments:
f()
 
Line 654 ⟶ 639:
; Partial application is impossible.
</syntaxhighlight>
 
=={{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.
 
<syntaxhighlight 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
Line 667 ⟶ 651:
 
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.
<syntaxhighlight lang="axe">NOARG()
ARGS(1,5,42)</syntaxhighlight>
 
Since arguments are simply global variables, they are always optional and can be omitted from right to left.
<syntaxhighlight lang="axe">OPARG(1,2,3,4,5,6)
OPARG(1,2,3)
OPARG()</syntaxhighlight>
 
Somewhat similar to [[TI-83 BASIC]], the last evaluated expression becomes the return value of the function. However, this is distinct from the Ans variable. Return values can be captured just like any other expression.
<syntaxhighlight lang="axe">MATHS(2,4)→A
Disp GETSTR()</syntaxhighlight>
 
User-defined functions can be distinguished from language-defined functions by the fact that language-defined function names are composed of atomic tokens (usually with built-in parentheses) whereas user-defined function names are composed of individual characters. Also, because only uppercase letters are available by default in the OS, most user-defined names are all uppercase while language-defined names are mixed case.
<syntaxhighlight lang="axe">USER()
axeFunc()</syntaxhighlight>
 
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">function Copialo$ (txt$, siNo, final$)
nuevaCadena$ = ""
 
Line 726 ⟶ 707:
Igual que la entrada de FreeBASIC.
</pre>
 
 
=={{header|Batch File}}==
 
Batch files do not have a traditional "function" system like OOP languages, however this is the closest thing to it. The only difference between a block of code and a function is the way method you choose to invoke it. It's also worth noting that all batch files can be called from any other batch file, performing a function. A function should be put somewhere in the code where it will not be parsed unless the script is redirected there.
 
<syntaxhighlight lang="dos">
:: http://rosettacode.org/wiki/Call_a_function
:: Demonstrate the different syntax and semantics provided for calling a function.
Line 840 ⟶ 819:
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)</syntaxhighlight>
The parentheses can often be omitted:
<syntaxhighlight lang="bbcbasic">PRINT SQR 2</syntaxhighlight>
The name of a <b>user-defined function</b> must begin with <tt>FN</tt>. A call to it is also an expression:
<syntaxhighlight lang="bbcbasic">PRINT FN_foo(bar$, baz%)</syntaxhighlight>
(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</syntaxhighlight>
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</syntaxhighlight>
If it has arguments, they come in parentheses just as with a function:
<syntaxhighlight lang="bbcbasic">PROC_foo(bar$, baz%, quux)</syntaxhighlight>
Note that you <i>cannot tell from this syntax</i> which of the variables <tt>bar$</tt>, <tt>baz%</tt>, and <tt>quux</tt> are arguments provided to the procedure and which of them are return values from it. You have to look at where it is defined:
<syntaxhighlight lang="bbcbasic">DEF PROC_foo(a$, RETURN b%, RETURN c)</syntaxhighlight>
<b>Subroutines</b> are provided for compatibility with older, unstructured dialects of BASIC; otherwise they are never really used. They require statements to be numbered, and they can neither receive arguments nor return values: they can only manipulate global variables. The <tt>GOSUB</tt> and <tt>RETURN</tt> statements in fact mirror assembly language 'jump to subroutine' and 'return from subroutine' instructions quite closely.
<syntaxhighlight lang="bbcbasic">200 GOSUB 30050</syntaxhighlight>
 
 
 
=={{header|BQN}}==
 
Line 869 ⟶ 844:
'''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"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.
Line 875 ⟶ 850:
'''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.
Line 885 ⟶ 860:
'''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
Line 894 ⟶ 869:
'''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.
Line 911 ⟶ 886:
'''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 920 ⟶ 894:
Strictly speaking, all Bracmat functions receive at least one argument. But empty strings are valid expressions, so you can do
 
<syntaxhighlight lang="bracmat">aFunctionWithoutArguments$</syntaxhighlight>
or
<syntaxhighlight lang="bracmat">aFunctionWithoutArguments'</syntaxhighlight>
 
Both function calls pass the right and side of the <code>$</code> or <code>'</code> operator. This is in fact still something: an empty string.
Line 949 ⟶ 923:
 
You can do
<syntaxhighlight lang="bracmat">func$!myargument;</syntaxhighlight>
The <code>;</code> marks the end of a Bracmat statement.
 
Line 956 ⟶ 930:
(Copied from JavaScript:) Bracmat functions are first-class citizens; they can be stored in variables and passed as arguments. Assigning to a variable <code>yourfunc</code> can be done in a few ways. The most common one is
 
<syntaxhighlight lang="bracmat">(yourfunc=local vars.function body)</syntaxhighlight>
If there is already a function <code>myfunc</code> that you want to assign to <code>yourfunc</code> as well, do
<syntaxhighlight lang="bracmat">('$myfunc:(=?yourfunc))</syntaxhighlight>
 
* Obtaining the return value of a function
 
<syntaxhighlight lang="bracmat">myfunc$!myarg:?myresult</syntaxhighlight>
 
Notice that the returned value can be any evaluated expression.
Line 974 ⟶ 948:
You can ignore the return value of a function <code>myfunc</code> as follows:
 
<syntaxhighlight lang="bracmat">myfunc$!myarg&yourfunc$!yourarg</syntaxhighlight>
 
But notice that if <code>myfunc</code> fails, the above expression returns the value produced by <code>myfunc</code>! To also ignore the success/failure of a function, do
 
<syntaxhighlight lang="bracmat">`(myfunc$!myarg)&yourfunc$!yourarg</syntaxhighlight>
 
* Stating whether arguments are passed by value or by reference
Line 988 ⟶ 962:
There is no special syntax for that, but you can write a function that e.g., can take a list with one or with two elements and that returns a function in the first case.
 
<syntaxhighlight lang="bracmat">( ( plus
= a b
. !arg:%?a ?b
Line 1,003 ⟶ 977:
<pre>1+2, not partial: 3
1+2, partial: 3</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">/* function with no argument */
f();
 
Line 1,070 ⟶ 1,043:
/* Scalar values are passed by value by default. However, arrays are passed by reference. */
/* Pointers *sort of* work like references, though. */</syntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="c sharp">
/* a function that has no argument */
public int MyFunction();
Line 1,104 ⟶ 1,076:
int returnValue = MyFunction();
</syntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang=C"c++">
 
/* function with no arguments */
Line 1,112 ⟶ 1,083:
</syntaxhighlight>
 
<syntaxhighlight lang=C"c++">
/* passing arguments by value*/
/* function with one argument */
Line 1,120 ⟶ 1,091:
</syntaxhighlight>
 
<syntaxhighlight lang=C"c++">
/* get return value of a function */
variable = function(args);
</syntaxhighlight>
 
<syntaxhighlight lang=C"c++">
#include <iostream>
using namespace std;
Line 1,141 ⟶ 1,112:
}
</syntaxhighlight>
 
=={{header|COBOL}}==
<syntaxhighlight lang=cobol>CALL "No-Arguments"
 
*> Fixed number of arguments.
CALL "2-Arguments" USING Foo Bar
 
CALL "Optional-Arguments" USING Foo
CALL "Optional-Arguments" USING Foo Bar
*> If an optional argument is omitted and replaced with OMITTED, any following
*> arguments can still be specified.
CALL "Optional-Arguments" USING Foo OMITTED Bar
*> Interestingly, even arguments not marked as optional can be omitted without
*> a compiler warning. It is highly unlikely the function will still work,
*> however.
CALL "2-Arguments" USING Foo
 
*> COBOL does not support a variable number of arguments, or named arguments.
 
*> Values to return can be put in either one of the arguments or, in OpenCOBOL,
*> the RETURN-CODE register.
*> A standard function call cannot be done in another statement.
CALL "Some-Func" USING Foo
MOVE Return-Code TO Bar
 
*> Intrinsic functions can be used in any place a literal value may go (i.e. in
*> statements) and are optionally preceded by FUNCTION.
*> Intrinsic functions that do not take arguments may optionally have a pair of
*> empty parentheses.
*> Intrinsic functions cannot be defined by the user.
MOVE FUNCTION PI TO Bar
MOVE FUNCTION MEDIAN(4, 5, 6) TO Bar
 
*> Built-in functions/subroutines typically have prefixes indicating which
*> compiler originally incorporated it:
*> - C$ - ACUCOBOL-GT
*> - CBL_ - Micro Focus
*> - CBL_OC_ - OpenCOBOL
*> Note: The user could name their functions similarly if they wanted to.
CALL "C$MAKEDIR" USING Foo
CALL "CBL_CREATE_DIR" USING Foo
CALL "CBL_OC_NANOSLEEP" USING Bar
*> Although some built-in functions identified by numbers.
CALL X"F4" USING Foo Bar
*> Parameters can be passed in 3 different ways:
*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may
*> be omitted. The address of the argument is passed to the function.
*> The function is allowed to modify the variable.
*> - BY CONTENT - a copy is made and the function is passed the address
*> of the copy, which it can then modify. This is recomended when
*> passing a literal to a function.
*> - BY VALUE - the function is passed the address of the argument (like a
*> pointer). This is mostly used to provide compatibility with other
*> languages, such as C.
CALL "Modify-Arg" USING BY REFERENCE Foo *> Foo is modified.
CALL "Modify-Arg" USING BY CONTENT Foo *> Foo is unchanged.
CALL "C-Func" USING BY VALUE Bar
 
*> Partial application is impossible as COBOL does not support first-class
*> functions.
*> However, as functions are called using a string of their PROGRAM-ID,
*> you could pass a 'function' as an argument to another function, or store
*> it in a variable, or get it at runtime.
ACCEPT Foo *> Get a PROGRAM-ID from the user.
CALL "Use-Func" USING Foo
CALL Foo USING Bar</syntaxhighlight>
 
=={{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"
Line 1,221 ⟶ 1,124:
</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"
Line 1,230 ⟶ 1,133:
'''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)"
Line 1,249 ⟶ 1,152:
 
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))
Line 1,268 ⟶ 1,171:
'''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"
Line 1,284 ⟶ 1,187:
'''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))
Line 1,298 ⟶ 1,201:
 
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"
Line 1,319 ⟶ 1,222:
 
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
Line 1,338 ⟶ 1,241:
</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]
Line 1,359 ⟶ 1,262:
</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))
Line 1,376 ⟶ 1,279:
</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
Line 1,399 ⟶ 1,302:
</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
 
Line 1,410 ⟶ 1,313:
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"
Line 1,433 ⟶ 1,336:
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
Line 1,451 ⟶ 1,354:
(discount-10pc-option-2 100); => 90
</syntaxhighlight>
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">CALL "No-Arguments"
 
*> Fixed number of arguments.
CALL "2-Arguments" USING Foo Bar
 
CALL "Optional-Arguments" USING Foo
CALL "Optional-Arguments" USING Foo Bar
*> If an optional argument is omitted and replaced with OMITTED, any following
*> arguments can still be specified.
CALL "Optional-Arguments" USING Foo OMITTED Bar
*> Interestingly, even arguments not marked as optional can be omitted without
*> a compiler warning. It is highly unlikely the function will still work,
*> however.
CALL "2-Arguments" USING Foo
 
*> COBOL does not support a variable number of arguments, or named arguments.
 
*> Values to return can be put in either one of the arguments or, in OpenCOBOL,
*> the RETURN-CODE register.
*> A standard function call cannot be done in another statement.
CALL "Some-Func" USING Foo
MOVE Return-Code TO Bar
 
*> Intrinsic functions can be used in any place a literal value may go (i.e. in
*> statements) and are optionally preceded by FUNCTION.
*> Intrinsic functions that do not take arguments may optionally have a pair of
*> empty parentheses.
*> Intrinsic functions cannot be defined by the user.
MOVE FUNCTION PI TO Bar
MOVE FUNCTION MEDIAN(4, 5, 6) TO Bar
 
*> Built-in functions/subroutines typically have prefixes indicating which
*> compiler originally incorporated it:
*> - C$ - ACUCOBOL-GT
*> - CBL_ - Micro Focus
*> - CBL_OC_ - OpenCOBOL
*> Note: The user could name their functions similarly if they wanted to.
CALL "C$MAKEDIR" USING Foo
CALL "CBL_CREATE_DIR" USING Foo
CALL "CBL_OC_NANOSLEEP" USING Bar
*> Although some built-in functions identified by numbers.
CALL X"F4" USING Foo Bar
*> Parameters can be passed in 3 different ways:
*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may
*> be omitted. The address of the argument is passed to the function.
*> The function is allowed to modify the variable.
*> - BY CONTENT - a copy is made and the function is passed the address
*> of the copy, which it can then modify. This is recomended when
*> passing a literal to a function.
*> - BY VALUE - the function is passed the address of the argument (like a
*> pointer). This is mostly used to provide compatibility with other
*> languages, such as C.
CALL "Modify-Arg" USING BY REFERENCE Foo *> Foo is modified.
CALL "Modify-Arg" USING BY CONTENT Foo *> Foo is unchanged.
CALL "C-Func" USING BY VALUE Bar
 
*> Partial application is impossible as COBOL does not support first-class
*> functions.
*> However, as functions are called using a string of their PROGRAM-ID,
*> you could pass a 'function' as an argument to another function, or store
*> it in a variable, or get it at runtime.
ACCEPT Foo *> Get a PROGRAM-ID from the user.
CALL "Use-Func" USING Foo
CALL Foo USING Bar</syntaxhighlight>
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
# Calling a function that requires no arguments
foo()
Line 1,506 ⟶ 1,475:
add2 1 #=> 3
</syntaxhighlight>
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
;Calling a function that requires no arguments
(defun a () "This is the 'A' function")
Line 1,535 ⟶ 1,503:
(funcall (curry #'+ 1) 2)
</syntaxhighlight>
 
=={{header|Cubescript}}==
<syntaxhighlight lang=Cubescript"cubescript">
// No arguments
myfunction
Line 1,555 ⟶ 1,522:
if (strcmp $myfunction "") [echo builtin function] // false
</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">import std.traits;
 
enum isSubroutine(alias F) = is(ReturnType!F == void);
Line 1,663 ⟶ 1,629:
<pre>true
false</pre>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">void main() {
// Function definition
// See the "Function definition" task for more info
Line 1,695 ⟶ 1,660:
var value = returnsValue();
}</syntaxhighlight>
 
=={{header|Delphi}}==
Delphi allows everything what [[#Pascal|Pascal]] allows.
Line 1,701 ⟶ 1,665:
 
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"dyalect">func foo() { }
foo()</syntaxhighlight>
 
Calling a function with a fixed number of arguments:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo(x, y, z) { }
foo(1, 2, 3)</syntaxhighlight>
 
Calling a function with optional arguments:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo(x, y = 0, z = 1) { }
foo(1)</syntaxhighlight>
 
Calling a function with a variable number of arguments:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo(args...) { }
foo(1, 2, 3)</syntaxhighlight>
 
Calling a function with named arguments:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo(x, y, z) { }
foo(z: 3, x: 1, y: 2)</syntaxhighlight>
 
Using a function in statement context:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo() { }
if true {
foo()
Line 1,756 ⟶ 1,718:
Using a function in first-class context within an expression:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo() { }
var x = if foo() {
1
Line 1,765 ⟶ 1,727:
Obtaining the return value of a function:
 
<syntaxhighlight lang=Dyalect"dyalect">func foo(x) { x * 2 }
var x = 2
var y = foo(x)</syntaxhighlight>
Line 1,771 ⟶ 1,733:
Distinguishing built-in functions and user-defined functions:
 
<syntaxhighlight lang=Dyalect"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
 
Line 1,785 ⟶ 1,747:
Distinguishing subroutines and functions:
 
<syntaxhighlight lang=Dyalect"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>
Line 1,791 ⟶ 1,753:
Stating whether arguments are passed by value or by reference:
 
<syntaxhighlight lang=Dyalect"dyalect">//All arguments are passed by reference</syntaxhighlight>
 
Is partial application possible and how:
 
<syntaxhighlight lang=Dyalect"dyalect">//Using a closure:
func apply(fun, fst) { snd => fun(fst, snd) }
 
Line 1,810 ⟶ 1,772:
var sub3 = apply(flip(sub), 3)
x = sub3(9) //x is 6</syntaxhighlight>
 
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu"># all functions used are from the standard library
# calling a function with no arguments:
random-int
Line 1,844 ⟶ 1,805:
# a function's arity is a property of its behavior and not
# of its definition</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.1:
Declaring closures
<syntaxhighlight lang="elena">
var c0 := { console.writeLine("No argument provided") };
var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") };
</syntaxhighlight>
Calling a closure without arguments
<syntaxhighlight lang="elena">
c0();
</syntaxhighlight>
Calling a closure with arguments
<syntaxhighlight lang="elena">
c2(2,4);
</syntaxhighlight>
Passing arguments by reference:
<syntaxhighlight lang="elena">
var exch := (ref object x){ x := 2 };
var a := 1;
exch(ref a);
</syntaxhighlight>
 
=={{header|Elixir}}==
 
<syntaxhighlight lang="elixir">
# Anonymous function
 
Line 1,928 ⟶ 1,887:
end
</syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
no_argument()
one_argument( Arg )
Line 1,944 ⟶ 1,902:
% Partial application is possible (a function returns a function that has one argument bound)
</syntaxhighlight>
 
=={{header|F Sharp|F#}}==
<syntaxhighlight lang="fsharp">// No arguments
noArgs()
 
Line 1,989 ⟶ 1,946:
// Partial application example
let add2 = (+) 2</syntaxhighlight>
 
=={{header|Factor}}==
* Calling a word with no arguments:
<syntaxhighlight lang=Factor"factor">foo</syntaxhighlight>
 
* Calling a word with a fixed number of arguments. This will pull as many objects as it needs from the stack. If there are not enough, it will result in a stack underflow.
<syntaxhighlight lang=Factor"factor">foo</syntaxhighlight>
 
* 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:
<syntaxhighlight lang=Factor"factor">"a" "b" "c" 3 narray
! { "a" "b" "c" }</syntaxhighlight>
 
* The named arguments idiom is to define a tuple, set its slots, and pass it to a word:
<syntaxhighlight lang=Factor"factor"><email>
"jack@aol.com" >>from
{ "jill@aol.com" } >>to
Line 2,012 ⟶ 1,968:
 
* First-class context: this pushes a word to the stack. Use execute to evaluate.
<syntaxhighlight lang=Factor"factor">\ foo</syntaxhighlight>
Additionally, you can put words directly inside sequences and quotations for deferred execution:
<syntaxhighlight lang=Factor"factor">{ foo } [ foo ]</syntaxhighlight>
 
* Obtaining the return value, which will be placed on the stack:
<syntaxhighlight lang=Factor"factor">foo</syntaxhighlight>
 
* Returns true if the word is defined in the Factor VM as opposed to in a vocabulary. It should be noted that there are very few primitives.
<syntaxhighlight lang=Factor"factor">\ foo primitive?</syntaxhighlight>
 
* Factor makes no distinction between subroutines and functions.
Line 2,027 ⟶ 1,983:
 
* Partial application is possible by use of curry. Here, the object 2 is curried into the left side of the quotation (anonymous function) <tt>[ - ]</tt>:
<syntaxhighlight lang=Factor"factor">{ 1 2 3 } 2 [ - ] curry map .
! { -1 0 1 }</syntaxhighlight>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">a-function \ requiring no arguments
a-function \ with a fixed number of arguents
a-function \ having optional arguments
Line 2,056 ⟶ 2,011:
: right ( n -- ) 0 move ;
: left ( n -- ) negate right ;</syntaxhighlight>
 
=={{header|Fortran}}==
===Examples===
<syntaxhighlight lang=Fortran"fortran">program main
implicit none
integer :: a
Line 2,162 ⟶ 2,116:
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 <syntaxhighlight lang=Fortran"fortran"> REAL this,that
DIST(X,Y,Z) = SQRT(X**2 + Y**2 + Z**2) + this/that !One arithmetic statement, possibly lengthy.
...
Line 2,170 ⟶ 2,124:
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 <syntaxhighlight lang=Fortran"fortran"> H = A + B
IF (blah) H = 3*H - 7</syntaxhighlight>
As written, the appearance of <code>H</code> on the right-hand side of an expression does ''not'' constitute a call of function <code>H</code> at all. Some compilers fail to deal with this as hoped, and so one must use a scratch variable such as <code>FH</code> to develop the value, then remember to ensure that the assignment <code>H = FH</code> is executed before exiting the function, by whatever route. If the result is a large datum (a long character variable, say) this is annoying.
Line 2,176 ⟶ 2,130:
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 <syntaxhighlight lang=Fortran"fortran"> REAL FUNCTION INTG8(F,A,B,DX) !Integrate function F.
EXTERNAL F !Some function of one parameter.
REAL A,B !Bounds.
Line 2,205 ⟶ 2,159:
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 <syntaxhighlight lang=Fortran"fortran"> TYPE MIXED
CHARACTER*12 NAME
INTEGER STUFF
Line 2,211 ⟶ 2,165:
TYPE(MIXED) LOTS(12000)</syntaxhighlight>
One might hope to try <code>IT = BCHOP(LOTS.NAME,"Fred")</code> where BCHOP is a well-tested function for performing a binary search that should run swiftly. Alas, no. The successive values of NAME are not contiguous while BCHOP expects to receive an array of values that are contiguous - that is, with a "stride" of one. So, the compiler inserts code to copy all the LOTS.NAME elements into such a work area and passes the location of that to BCHOP (which searches it swiftly), then on return, the work area is copied back to LOTS.NAME just in case there had been a change. This latter can be avoided if within BCHOP its array is given the attribute INTENT(IN) for read-only but the incoming copy still means an effort of order N, while for the search the effort is just Log(N). This can have a less-than-subtle effect if large arrays are involved.
 
=={{header|Fortress}}==
<syntaxhighlight lang="fortress">
component call_a_function
export Executable
Line 2,253 ⟶ 2,206:
end
</syntaxhighlight>
=={{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!"
Line 2,299 ⟶ 2,254:
 
1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'</pre>
 
=={{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|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
<syntaxhighlight lang="gambas">Public Sub Main()
 
Hello
Line 2,339 ⟶ 2,288:
Hello Hello Hello!!
</pre>
 
=={{header|Go}}==
The following examples use functions from the standard packages
plus a few dummy local functions:
::<syntaxhighlight lang="go">import (
"image"
"image/gif"
Line 2,355 ⟶ 2,303:
func h(string, ...int) {}</syntaxhighlight>
* Calling with no arguments and calling with a fixed number of arguments:
::<syntaxhighlight lang="go"> f()
g(1, 2.0)
// If f() is defined to return exactly the number and type of
Line 2,365 ⟶ 2,313:
g(g(1, 2.0), 3.0)</syntaxhighlight>
* 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). <syntaxhighlight lang="go"> h("ex1")
h("ex2", 1, 2)
h("ex3", 1, 2, 3, 4)
Line 2,374 ⟶ 2,322:
//h("fail", 2, list...)</syntaxhighlight>
* 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>). <syntaxhighlight lang="go"> gif.Encode(ioutil.Discard, image.Black, &gif.Options{NumColors: 16})</syntaxhighlight>
* Optional arguments are supported.
::<syntaxhighlight lang="go">package main
 
import "fmt"
Line 2,391 ⟶ 2,339:
}</syntaxhighlight>
* Named arguments are supported.
::<syntaxhighlight lang="go">package main
 
import "fmt"
Line 2,407 ⟶ 2,355:
}</syntaxhighlight>
* Within a statement context.
::Assignment statements are shown later. Only functions returning a single value can be used in a single value context: <syntaxhighlight lang="go"> if 2*g(1, 3.0)+4 > 0 {}</syntaxhighlight>
* In a first-class context:
::<syntaxhighlight lang="go"> fn := func(r rune) rune {
if unicode.IsSpace(r) {
return -1
Line 2,419 ⟶ 2,367:
strings.Map(func(r rune) rune { return r + 1 }, "shift")</syntaxhighlight>
* 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</syntaxhighlight>
* 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). <syntaxhighlight lang="go"> list = append(list, a, d, e, i)
i = len(list)</syntaxhighlight>
* Go has no subroutines, just functions and methods.
Line 2,430 ⟶ 2,378:
::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
::<syntaxhighlight lang="go">package main
 
import "fmt"
Line 2,453 ⟶ 2,401:
* 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"
Line 2,480 ⟶ 2,428:
fmt.Println(partial(5)) //prt 18
}</syntaxhighlight>
 
=={{header|Groovy}}==
There are two types of first-class functions in Groovy.
Line 2,489 ⟶ 2,436:
 
* 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")
Line 2,501 ⟶ 2,448:
 
* 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")
Line 2,510 ⟶ 2,457:
 
* 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 }
Line 2,531 ⟶ 2,478:
 
* 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
Line 2,544 ⟶ 2,491:
* Is partial application possible and how
Partial application in Groovy is performed via currying (demonstrated above)
 
=={{header|Haskell}}==
 
<syntaxhighlight lang="haskell">
-- Calling a function with a fixed number of arguments
multiply x y = x * y
Line 2,577 ⟶ 2,523:
-- Stating whether arguments are passed by value or by reference
</syntaxhighlight>
 
=={{header|i}}==
<syntaxhighlight lang="i">//The type of the function argument determines whether or not the value is passed by reference or not.
//Eg. numbers are passed by value and lists/arrays are passed by reference.
 
Line 2,608 ⟶ 2,553:
}
</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon have generalized procedures and syntax that are used to implement functions, subroutines and generators.
Line 2,621 ⟶ 2,565:
For more information see [[Icon%2BUnicon/Intro|Icon and Unicon Introduction on Rosetta]]
 
<syntaxhighlight lang=Icon"icon">procedure main() # demonstrate and describe function calling syntax and semantics
 
# normal procedure/function calling
Line 2,651 ⟶ 2,595:
f("x:=",1,"y:=",2) # named parameters (user defined)
end</syntaxhighlight>
 
=={{header|J}}==
 
Line 2,658 ⟶ 2,601:
A verb, in J, typically supports two syntactic variants:
 
<syntaxhighlight lang="j"> verb noun
noun verb noun</syntaxhighlight>
 
Line 2,665 ⟶ 2,608:
An argument list can be represented by an array. Thus, when dealing with multiple arguments, a typical form is:
 
<syntaxhighlight lang="j"> function argumentList</syntaxhighlight>
 
Here, <code>function</code> is a verb and <code>argumentList</code> is a noun.
Line 2,671 ⟶ 2,614:
For example:
 
<syntaxhighlight lang="j"> sum(1,2,3)</syntaxhighlight>
 
Here <code>sum</code> is a verb and <code>(1,2,3)</code> is a noun.
Line 2,677 ⟶ 2,620:
Thus:
 
''A function that requires no arguments'' can be simulated by calling a function with empty argument list: <syntaxhighlight lang="j">f''</syntaxhighlight> Note that an empty list of characters is not the only constant in the language which is an empty list. That said, most operations in the language do not care what type of data is not present, in an array which contains nothing.
 
 
''A function with a fixed number of arguments'' gets special treatment in J when the fixed number is 1 or 2. <syntaxhighlight lang="j">f 'one argument'</syntaxhighlight>and <syntaxhighlight lang="j">'this example has two arguments' f 'the other argument'</syntaxhighlight> Alternatively, the function can be written such that an argument list is an error when it's the wrong length.
 
''A function with a variable number of arguments (varargs)'': See above.
 
If argument types conflict they will need to be put in boxes and the function will have to take its arguments out of the boxes. Here's an unboxed example with five arguments: <syntaxhighlight lang="j"> f 1,2,3,4,5</syntaxhighlight> and here's a boxed example with five arguments: <syntaxhighlight lang="j">f (<1),(<2),(<3),(<4),(<5) </syntaxhighlight> Note that the last set of parenthesis is unnecessary <syntaxhighlight lang="j">f (<1),(<2),(<3),(<4),<5</syntaxhighlight> Note also that J offers some syntactic sugar for this kind of list <syntaxhighlight lang="j">f 1; 2; 3; 4; <5</syntaxhighlight>. Note also that if the last argument in a semicolon list is not boxed there is no need to explicitly box it, since that is unambiguous (it must be boxed so that it conforms with the other members of the list). <syntaxhighlight lang="j">f 1; 2; 3; 4; 5</syntaxhighlight>
 
''A function with named arguments'' can be accomplished by calling a function with the names of the arguments. <syntaxhighlight lang="j">f 'george';'tom';'howard'</syntaxhighlight> Other interpretations of this concept are also possible. For example, the right argument for a verb might be a list of argument names and the left argument might be a corresponding list of argument values: <syntaxhighlight lang="j">1 2 3 f 'george';'tom';'howard'</syntaxhighlight> Or, for example a function which requires an object could be thought of as a function with named arguments since an object's members have names:<syntaxhighlight lang="j"> obj=: conew'blank'
george__obj=: 1
tom__obj=: 2
howard__obj=: 3
f obj
coerase obj</syntaxhighlight> Name/value pairs can also be used for this purpose and can be implemented in various ways, including passing names followed by values <syntaxhighlight lang="j">f 'george';1;'tom';2;'howard';3</syntaxhighlight> and passing a structure of pairs <syntaxhighlight lang="j">f ('george';1),('tom';2),:(howard';3)</syntaxhighlight> Or, for example, the pairs could be individually boxed: <syntaxhighlight lang="j">f ('george';1);('tom';2);<howard';3</syntaxhighlight>
 
''Using a function in command context'' is no different from using a function in any other context, in J. ''Using a function in first class context within an expression'' is no different from using a function in any other context, in J.
 
''Obtaining the return value of a function'' is no different from using a function in j. For example, here we add 1 to the result of a function: <syntaxhighlight lang="j">1 + f 2</syntaxhighlight>
 
The only ''differences that apply to calling builtin functions rather than user defined functions'' is spelling of the function names.
 
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}}==
Java does not have functions, but Java classes have "methods" which are equivalent.
 
* Calling a function that requires no arguments
<syntaxhighlight lang="java">myMethod()</syntaxhighlight>
We didn't specify an object (or a class) as the location of the method, so <tt>this.myMethod()</tt> is assumed. This applies to all the following examples.
 
* Calling a function with a fixed number of arguments
<syntaxhighlight lang="java">myMethod(97, 3.14)</syntaxhighlight>
 
* Calling a function with optional arguments
This is possible if the method name is overloaded with different argument lists. For example:
<syntaxhighlight lang="java">int myMethod(int a, double b){
// return result of doing sums with a and b
}
Line 2,722 ⟶ 2,664:
 
The compiler figures out which method to call based on the types of the arguments, so in this case the second argument appears to be optional. If you omit it, the value <tt>1.414</tt> is used.
<syntaxhighlight lang="java">System.out.println( myMethod( 97, 3.14 ) );
System.out.println( myMethod( 97 ) );</syntaxhighlight>
 
* Calling a function with a variable number of arguments
This is possible if the method is defined with varargs syntax. For example:
<syntaxhighlight lang="java">void printAll(String... strings){
for ( String s : strings )
System.out.println( s );
Line 2,733 ⟶ 2,675:
 
The type of <tt>strings</tt> is actually a string array, but the caller just passes strings:
<syntaxhighlight lang="java">printAll( "Freeman" );
printAll( "Freeman", "Hardy", "Willis" );</syntaxhighlight>
 
Line 2,740 ⟶ 2,682:
* Calling a function with named arguments
Not directly possible, but you could simulate this (somewhat verbosely):
<syntaxhighlight lang="java">int myMethod( Map<String,Object> params ){
return
((Integer)params.get("x")).intValue()
Line 2,747 ⟶ 2,689:
 
Called like this:
<syntaxhighlight lang="java">System.out.println( myMethod(new HashMap<String,Object>(){{put("x",27);put("y",52);}}) );</syntaxhighlight>
 
Yuk.
Line 2,758 ⟶ 2,700:
 
* Obtaining the return value of a function
<syntaxhighlight lang="java">int i = myMethod(x);</syntaxhighlight>
 
* Distinguishing built-in functions and user-defined functions
Line 2,768 ⟶ 2,710:
* 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:
<syntaxhighlight lang="java">myMethod(List<String> list){
// If I change the contents of the list here, the caller will see the change
}</syntaxhighlight>
Line 2,774 ⟶ 2,716:
* Is partial application possible and how
Don't know
 
=={{header|JavaScript}}==
 
The arguments to a JavaScript function are stored in a special array-like object which does not enforce arity in any way; a function declared to take ''n'' arguments may be called with none‒and vice versa‒without raising an error.
 
<syntaxhighlight lang=JavaScript"javascript">var foo = function() { return arguments.length };
foo() // 0
foo(1, 2, 3) // 3</syntaxhighlight>
Line 2,786 ⟶ 2,727:
 
JavaScript functions are first-class citizens; they can be stored in variables (see above) and passed as arguments.
<syntaxhighlight lang=JavaScript"javascript">var squares = [1, 2, 3].map(function (n) { return n * n }); // [1, 4, 9]</syntaxhighlight>
 
Naturally, they can also be returned, thus partial application is supported.
<syntaxhighlight lang=JavaScript"javascript">
var make_adder = function(m) {
return function(n) { return m + n }
Line 2,798 ⟶ 2,739:
Calling a user-defined function's <tt>toString()</tt> method returns its source verbatim; that the implementation is elided for built-ins provides a mechanism for distinguishing between the two.
 
<syntaxhighlight lang=JavaScript"javascript">foo.toString()
"function () { return arguments.length }"
alert.toString()
Line 2,804 ⟶ 2,745:
 
Arguments are passed by value, but the members of collections are essentially passed by reference and thus propagate modification.
<syntaxhighlight lang=JavaScript"javascript">var mutate = function(victim) {
victim[0] = null;
victim = 42;
Line 2,810 ⟶ 2,751:
var foo = [1, 2, 3];
mutate(foo) // foo is now [null, 2, 3], not 42</syntaxhighlight>
 
=={{header|jq}}==
jq functions are pure functions that are somewhat unusual in two respects:
Line 2,875 ⟶ 2,815:
 
See [[Currying#jq]].
 
=={{header|Julia}}==
<syntaxhighlight lang=Julia"julia">
# Calling a function that requires no arguments:
f() = print("Hello world!")
Line 2,969 ⟶ 2,908:
map(x -> f(x, 10), v) # v = [30, 52, 82]
</syntaxhighlight>
 
=={{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="scala">// version 1.0.6
 
fun fun1() = println("No arguments")
Line 3,021 ⟶ 2,959:
Hello world
</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
Line 3,074 ⟶ 3,011:
More can be seen in http://lambdaway.free.fr/lambdawalks/?view=lambda
</syntaxhighlight>
 
 
 
=={{header|langur}}==
User-defined and built-in functions can be called using parentheses.
Line 3,083 ⟶ 3,017:
 
=== 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(
f(.sum, .i, .c) .sum + toNumber(.c, 36) x .weight[.i],
0,
Line 3,109 ⟶ 3,043:
# 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)
Line 3,128 ⟶ 3,061:
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 3,144 ⟶ 3,076:
 
In some module, define the following:
<syntaxhighlight lang="lisp">
(defun my-func()
(: io format '"I get called with NOTHING!~n"))
Line 3,150 ⟶ 3,082:
 
Then you use it like so (depending upon how you import it):
<syntaxhighlight lang="lisp">
> (my-func)
I get called with NOTHING!
Line 3,158 ⟶ 3,090:
'''Calling a function with a fixed number of arguments:'''
In some module, define the following:
<syntaxhighlight lang="lisp">
(defun my-func(a b)
(: io format '"I got called with ~p and ~p~n" (list a b)))
Line 3,164 ⟶ 3,096:
 
Then you use it like so:
<syntaxhighlight lang="lisp">
> (my-func '"bread" '"cheese")
I got called with "bread" and "cheese"
Line 3,176 ⟶ 3,108:
* One can define multiple functions so that it ''appears'' that one is calling a function with optional or a variable number of arguments:
 
<syntaxhighlight lang="lisp">
(defmodule args
(export all))
Line 3,194 ⟶ 3,126:
 
Here is some example usage:
<syntaxhighlight lang="lisp">
> (slurp '"args.lfe")
#(ok args)
Line 3,221 ⟶ 3,153:
 
'''Using a function in statement context:'''
<syntaxhighlight lang="lisp">
...
(cond ((== count limit) (hit-limit-func arg-1 arg-2))
Line 3,231 ⟶ 3,163:
 
From the LFE REPL:
<syntaxhighlight lang="lisp">
> (>= 0.5 (: math sin 0.5))
true
Line 3,239 ⟶ 3,171:
 
There are many, many ways to assign function outputs to variables in LFE. One fairly standard way is with the <code>(let ...)</code> form:
<syntaxhighlight lang="lisp">
(let ((x (: math sin 0.5)))
...)
Line 3,267 ⟶ 3,199:
* Not explicitly.
* However, one can use <code>lambda</code>s to achieve the same effect.
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'Call a function - Liberty BASIC
 
Line 3,313 ⟶ 3,244:
'impossible
</syntaxhighlight>
 
=={{header|Lingo}}==
 
*Calling a function that requires no arguments
<syntaxhighlight lang="lingo">foo()
-- or alternatively:
call(#foo, _movie)</syntaxhighlight>
 
*Calling a function with a fixed number of arguments
<syntaxhighlight lang="lingo">foo(1,2,3)
-- or alternatively:
call(#foo, _movie, 1, 2, 3)</syntaxhighlight>
 
*Calling a function with optional arguments
<syntaxhighlight lang="lingo">on foo (a, b)
if voidP(b) then b = 1
return a * b
end</syntaxhighlight>
<syntaxhighlight lang="lingo">put foo(23, 2)
-- 46
put foo(23)
Line 3,337 ⟶ 3,267:
 
*Calling a function with a variable number of arguments
<syntaxhighlight lang="lingo">on sum ()
res = 0
repeat with i = 1 to the paramCount
Line 3,344 ⟶ 3,274:
return res
end</syntaxhighlight>
<syntaxhighlight lang="lingo">put sum (1,2,3)
-- 6</syntaxhighlight>
 
Line 3,353 ⟶ 3,283:
*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:
<syntaxhighlight lang="lingo">----------------------------------------
-- One of the five native iterative methods defined in ECMAScript 5
-- @param {list} tList
Line 3,373 ⟶ 3,303:
return n*2
end</syntaxhighlight>
<syntaxhighlight lang="lingo">l = [1,2,3]
put map(l, #doubleInt)
-- [2, 4, 6]</syntaxhighlight>
 
*Obtaining the return value of a function
<syntaxhighlight lang="lingo">x = foo(1,2)</syntaxhighlight>
 
*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:
<syntaxhighlight lang="lingo">on getAllUserFunctions ()
res = []
repeat with i = 1 to _movie.castlib.count
Line 3,399 ⟶ 3,329:
return res
end</syntaxhighlight>
<syntaxhighlight lang="lingo">put getAllUserFunctions()
-- [#sum, #double, #getAllUserFunctions]</syntaxhighlight>
 
Line 3,407 ⟶ 3,337:
*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:
<syntaxhighlight lang="lingo">on double (someList)
cnt = someList.count
repeat with i = 1 to cnt
Line 3,413 ⟶ 3,343:
end repeat
end</syntaxhighlight>
<syntaxhighlight lang="lingo">l = [1,2,3]
double(l)
put l
Line 3,422 ⟶ 3,352:
put l
-- [1, 2, 3]</syntaxhighlight>
 
=={{header|Little}}==
 
Line 3,428 ⟶ 3,357:
local fuctions.
 
<syntaxhighlight lang=C"c">// Calling a function that requires no arguments
void foo() {puts("Calling a function with no arguments");}
foo();
Line 3,463 ⟶ 3,392:
puts (b);
}</syntaxhighlight>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped.
function fixed (a, b, c) print(a, b, c) end
fixed() --> nil nil nil
Line 3,498 ⟶ 3,426:
-- Built-in functions are not easily distinguishable from user-defined functions
</syntaxhighlight>
 
=={{header|Luck}}==
<syntaxhighlight lang="luck">/* Calling a function that requires no arguments */
f();;
 
Line 3,543 ⟶ 3,470:
/* 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);;</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<pre>
Line 3,629 ⟶ 3,555:
 
</pre>
 
=={{header|Maple}}==
Calling a function with no arguments:<syntaxhighlight lang=Maple"maple"> f()</syntaxhighlight>
Calling a function with a fixed number of arguments:<syntaxhighlight lang=Maple"maple">f(1,sin(x), g -> int(g(t),t=0..1)</syntaxhighlight>
Calling a function with optional arguments: <syntaxhighlight lang=Maple"maple">f(1, sin(x), g -> int(g(t),t=0..1)</syntaxhighlight>
Calling a function with a variable number of arguments: <syntaxhighlight lang=Maple"maple">f(1, sin(x), g -> int(g(t),t=0..1)</syntaxhighlight>
Calling a function with named arguments:<syntaxhighlight lang=Maple"maple">f(a,b,method = foo)</syntaxhighlight>
Calling a function in a statements context:<syntaxhighlight lang=Maple"maple">f(a); f(b);</syntaxhighlight>
Using a function in first-class context within an expression:<syntaxhighlight lang=Maple"maple">f(a) + g(b)</syntaxhighlight>
Obtaining the return value of a function:<syntaxhighlight lang=Maple"maple"> x := f(1)</syntaxhighlight>
Distinguishing built-in functions and user-defined functions:
<syntaxhighlight lang=Maple"maple">> type( op, 'builtin' );
true
</syntaxhighlight>
Line 3,649 ⟶ 3,574:
 
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[]</syntaxhighlight>
 
Calling a function with a fixed number of arguments:
<syntaxhighlight lang=Mathematica"mathematica">f[1,2]</syntaxhighlight>
 
Calling a function with optional arguments:
<syntaxhighlight lang=Mathematica"mathematica">f[1,Option1->True]</syntaxhighlight>
 
Calling a function with a variable number of arguments:
<syntaxhighlight lang=Mathematica"mathematica">f[1,Option1->True]
f[1,Option1->True,Option2->False]</syntaxhighlight>
 
Calling a function with named arguments:
<syntaxhighlight lang=Mathematica"mathematica">f[Option1->True,Option2->False]</syntaxhighlight>
 
Using a function in statement context:
<syntaxhighlight lang=Mathematica"mathematica">f[1,2];f[2,3]</syntaxhighlight>
 
Using a function in first-class context within an expression:
<syntaxhighlight lang=Mathematica"mathematica">(#^2)&[3];</syntaxhighlight>
 
The return value of a function can be formally extracted using Return[]
Line 3,677 ⟶ 3,601:
No formal distinction between subroutines and functions.
Arguments can be passed by value or by reference.
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab"matlab">
% Calling a function that requires no arguments
function a=foo();
Line 3,730 ⟶ 3,653:
% 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>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">// function with no arguments
no_args()
 
Line 3,750 ⟶ 3,672:
println "func is a built-in or doesn't exist"
end</syntaxhighlight>
 
=={{header|Nemerle}}==
<syntaxhighlight lang=Nemerle"nemerle">// no arguments
f()
 
Line 3,809 ⟶ 3,730:
def a = g(3) // equivalent to: def a = f(2, 3)
def b = h(3) // equivalent to: def b = f(3, 2)</syntaxhighlight>
 
=={{header|Nim}}==
Translated from Python, when possible:
<syntaxhighlight lang="nim">proc no_args() =
discard
# call
Line 3,855 ⟶ 3,775:
let y = 19.return_something() + 10
let z = 19.return_something + 10</syntaxhighlight>
 
=={{header|OCaml}}==
 
* Calling a function that requires no arguments:
 
<syntaxhighlight lang="ocaml">f ()</syntaxhighlight>
 
(In fact it is impossible to call a function without arguments, when there are no particular arguments we provide the type <code>unit</code> which is a type that has only one possible value. This type is mainly made for this use.)
Line 3,866 ⟶ 3,785:
* Calling a function with a fixed number of arguments:
 
<syntaxhighlight lang="ocaml">f 1 2 3</syntaxhighlight>
 
* Calling a function with optional arguments:
Line 3,872 ⟶ 3,791:
For a function that has this signature:
 
<syntaxhighlight lang="ocaml">val f : ?a:int -> int -> unit</syntaxhighlight>
 
here is how to call it with or without the first argument omited:
 
<syntaxhighlight lang="ocaml">f 10
f ~a:6 10</syntaxhighlight>
 
Due to partial application, an optional argument always has to be followed by a non-optional argument. If the function needs no additional arguments then we use the type <code>unit</code>:
 
<syntaxhighlight lang="ocaml">g ()
g ~b:1.0 ()</syntaxhighlight>
 
Line 3,894 ⟶ 3,813:
Named arguments are called '''labels'''.
 
<syntaxhighlight lang="ocaml">f ~arg:3</syntaxhighlight>
 
If a variable has the same name than the label we can use this simpler syntax:
 
<syntaxhighlight lang="ocaml">let arg = 3 in
f ~arg</syntaxhighlight>
 
* Using a function in statement context:
 
<syntaxhighlight lang="ocaml">(* TODO *)</syntaxhighlight>
 
* Using a function in first-class context within an expression:
Line 3,911 ⟶ 3,830:
* Obtaining the return value of a function:
 
<syntaxhighlight lang="ocaml">let ret = f ()
let a, b, c = f () (* if there are several returned values given as a tuple *)
let _ = f () (* if we want to ignore the returned value *)
Line 3,933 ⟶ 3,852:
 
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 3,941 ⟶ 3,859:
 
If f is a function and c b a ares objects :
<syntaxhighlight lang=Oforth"oforth">a b c f</syntaxhighlight>
will push c then b then a on the stack then call f. Calling f does not describe if f will use 1, 2 or 3 arguments (or none).
 
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)</syntaxhighlight>
 
Intepreter will replace this second syntax by the first one. It is only "sugar"...
 
<syntaxhighlight lang=Oforth"oforth">a b c f
a b f(c)
a f(b, c)
Line 3,958 ⟶ 3,876:
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</syntaxhighlight>
will call m with r as its receiver.
It is also possible to use the same "sugar" notation used by functions :
<syntaxhighlight lang=Oforth"oforth">r m(a, b, c)</syntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
; note: sign "==>" indicates expected output
 
Line 4,104 ⟶ 4,021:
; 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
Line 4,115 ⟶ 4,031:
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 4,122 ⟶ 4,037:
 
Functions can be used when statements would be expected without change.
<syntaxhighlight lang="parigp">f(); \\ zero arguments
sin(Pi/2); \\ fixed number of arguments
vecsort([5,6]) != vecsort([5,6],,4) \\ optional arguments
Line 4,133 ⟶ 4,048:
 
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:
<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).
Line 4,151 ⟶ 4,065:
* 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.
<syntaxhighlight lang="perl">foo(); # Call foo on the null list
&foo(); # Ditto
foo($arg1, $arg2); # Call foo on $arg1 and $arg2
Line 4,160 ⟶ 4,073:
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;</syntaxhighlight>
Call foo() with the current values of @_<syntaxhighlight lang="perl">&foo;</syntaxhighlight>
Call foo() with the current values of @_, discarding the previous stack frame. Not your grandfather's (harmful) goto, although the keyword can do both.<syntaxhighlight lang="perl">goto &foo;</syntaxhighlight>
For subroutines stored in references (anonymous subroutines).<syntaxhighlight lang="perl">&$fooref('foo', 'bar');
&{$fooref}('foo', 'bar');
$fooref->('foo', 'bar');</syntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Line 4,173 ⟶ 4,085:
* Phix does not allow implicit discard of function results. The explicit discard statement takes the form
 
<!--<syntaxhighlight lang=Phix"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>-->
Line 4,179 ⟶ 4,091:
* This is in fact a simple contraction of standard multiple assigment (which can be nested as deeply as you like):
 
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #0000FF;">{<span style="color: #000000;">cities<span style="color: #0000FF;">,<span style="color: #000000;">populations<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize<span style="color: #0000FF;">(<span style="color: #000000;">muncipalities<span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{<span style="color: #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>
Line 4,188 ⟶ 4,100:
* Optional arguments are denoted simply by the presence of a default, and must be grouped on the right:
 
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">b<span style="color: #0000FF;">=<span style="color: #008000;">"default"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{<span style="color: #000000;">a<span style="color: #0000FF;">,<span style="color: #000000;">b<span style="color: #0000FF;">}</span>
Line 4,200 ⟶ 4,112:
* Named arguments can be specified in any order, with an error if any non-optional parameters are missing:
 
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #0000FF;">?<span style="color: #000000;">myfunction<span style="color: #0000FF;">(<span style="color: #000000;">b<span style="color: #0000FF;">:=<span style="color: #008000;">"then"<span style="color: #0000FF;">,<span style="color: #000000;">a<span style="color: #0000FF;">:=<span style="color: #000000;">3<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- displays {3,"then"}
--?myfunction(b:="though") -- compile-time error
Line 4,208 ⟶ 4,120:
* Phix support first-class functions directly, as integers, along with an older routine_id mechanism:
 
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #008080;">constant</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">r_myfunction</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">routine_id<span style="color: #0000FF;">(<span style="color: #008000;">"myfunction"<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">first_class</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">myfunction</span>
Line 4,225 ⟶ 4,137:
* All arguments are passed by reference with copy-on-write semantics: to modify the value of a parameter you must both return and assign it, as in:
 
<!--<syntaxhighlight lang=Phix"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">def saludo
"Hola mundo" print nl
enddef
Line 4,239 ⟶ 4,150:
 
getid saludo exec</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):
<syntaxhighlight lang=PicoLisp"picolisp">(foo)
(bar 1 'arg 2 'mumble)</syntaxhighlight>
When a function is used in a "first class context" (e.g. passed to another function), then it is not yet '''called'''. It is simply '''used'''. Technically, a function can be either a '''number''' (a built-in function) or a '''list''' (a Lisp-level function) in PicoLisp):
<syntaxhighlight lang=PicoLisp"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</syntaxhighlight>
Any argument to a function may be evaluated or not, depending on the function. For example, 'setq' evaluates every second argument
<syntaxhighlight lang=PicoLisp"picolisp">(setq A (+ 3 4) B (* 3 4))</syntaxhighlight>
i.e. the first argument 'A' is not evaluated, the second evaluates to 7, 'B' is not evaluated, then the fourth evaluates to 12.
 
=={{header|PureBasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang=PureBasic"purebasic">Procedure Saludo()
PrintN("Hola mundo!")
EndProcedure
Line 4,293 ⟶ 4,202:
{{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).
<syntaxhighlight lang="python">def no_args():
pass
# call
Line 4,367 ⟶ 4,274:
## For partial function application see:
## http://rosettacode.org/wiki/Partial_function_application#Python</syntaxhighlight>
 
 
=={{header|QBasic}}==
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">FUNCTION Copialo$ (txt$, siNo, final$)
DIM nuevaCadena$
Line 4,409 ⟶ 4,314:
Igual que la entrada de FreeBASIC.
</pre>
 
 
=={{header|Quackery}}==
 
Line 4,446 ⟶ 4,349:
Stack empty.
</pre>
 
=={{header|R}}==
Translated from Python, when possible.
<syntaxhighlight lang="rsplus">### Calling a function that requires no arguments
no_args <- function() NULL
no_args()
Line 4,507 ⟶ 4,409:
### Is partial application possible and how
# Yes, see http://rosettacode.org/wiki/Partial_function_application#R</syntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang=Racket"racket">
#lang racket
 
Line 4,550 ⟶ 4,451:
(λ(x) (foo 1 2 x)) ; a direct way of doing the same
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 4,563 ⟶ 4,463:
Calling a function that requires no arguments:
 
<syntaxhighlight lang="raku" line>foo # as list operator
foo() # as function
foo.() # as function, explicit postfix form
Line 4,574 ⟶ 4,474:
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
Line 4,608 ⟶ 4,508:
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
Line 4,627 ⟶ 4,527:
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
Line 4,645 ⟶ 4,545:
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>
 
Line 4,656 ⟶ 4,556:
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
Line 4,681 ⟶ 4,581:
===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;
 
Line 4,774 ⟶ 4,674:
{{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===
<syntaxhighlight lang="rexx">/*REXX pgms demonstrates various methods/approaches of invoking/calling a REXX function.*/
 
/*╔════════════════════════════════════════════════════════════════════╗
Line 4,798 ⟶ 4,697:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function with a fixed number of arguments. ║
║ ║
Line 4,825 ⟶ 4,724:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function with optional arguments. ║
║ ║
Line 4,845 ⟶ 4,744:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function with a variable number of arguments. ║
║ ║
Line 4,874 ⟶ 4,773:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function in statement context. ║
║ ║
Line 4,892 ⟶ 4,791:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Obtaining the return value of a function. ║
║ ║
Line 4,905 ⟶ 4,804:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Distinguishing built-in functions and user-defined functions. ║
║ ║
Line 4,925 ⟶ 4,824:
 
 
<syntaxhighlight lang="rexx"> /*╔════════════════════════════════════════════════════════════════════╗
║ Distinguishing subroutines and functions. ║
║ ║
Line 4,951 ⟶ 4,850:
 
===version 2===
<syntaxhighlight lang="rexx">/* REXX ***************************************************************
* 29.07.2013 Walter Pachl trying to address the task concisely
***********************************************************************
Line 5,065 ⟶ 4,964:
rc=44 (Function or message did not return data)
fb cannot be invoked as function (it does not return a value)</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
hello()
func hello
see "Hello from function" + nl
</syntaxhighlight>
<syntaxhighlight lang="ring">
first() second()
func first see "message from the first function" + nl
func second see "message from the second function" + nl
</syntaxhighlight>
<syntaxhighlight lang="ring">
sum(3,5) sum(1000,2000)
func sum x,y see x+y+nl
</syntaxhighlight>
<syntaxhighlight lang="ring">
# this program will print the hello world message first then execute the main function
See "Hello World!" + nl
Line 5,087 ⟶ 4,985:
see "Message from the main function" + nl
</syntaxhighlight>
 
=={{header|Ruby}}==
Ruby does not have functions, but Ruby classes have "methods" which are equivalent.
Line 5,095 ⟶ 4,992:
 
*Calling a function that requires no arguments
:<syntaxhighlight lang="ruby">def foo() p "foo" end
 
foo #=> "foo"
Line 5,101 ⟶ 4,998:
 
*Calling a function with a fixed number of arguments
:<syntaxhighlight lang="ruby">def foo arg; p arg end # one argument
 
foo(1) #=> 1
Line 5,108 ⟶ 5,005:
 
*Calling a function with optional arguments
:<syntaxhighlight lang="ruby">def foo(x=0, y=x, flag=true) p [x,y,flag] end
 
foo #=> [0, 0, true]
Line 5,116 ⟶ 5,013:
 
*Calling a function with a variable number of arguments
:<syntaxhighlight lang="ruby">def foo(*args) p args end
 
foo #=> []
Line 5,122 ⟶ 5,019:
 
*Calling a function with named arguments
:<syntaxhighlight lang="ruby">def foo(id:0, name:"", age:0) p [id, name, age] end
 
foo(age:22, name:"Tom") #=> [0, "Tom", 22]</syntaxhighlight>
Line 5,134 ⟶ 5,031:
 
*Obtaining the return value of a function
:<syntaxhighlight lang="ruby">def foo(a,b) a + b end
 
bar = foo 10,20
Line 5,155 ⟶ 5,052:
::These methods are called without a receiver and thus can be called in functional form.
 
::<syntaxhighlight lang="ruby">puts "OK!" # Kernel#puts
raise "Error input" # Kernel#raise
Integer("123") # Kernel#Integer
Line 5,180 ⟶ 5,077:
::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>.
::<syntaxhighlight lang="ruby">class Array
def sum(init=0, &blk)
if blk
Line 5,197 ⟶ 5,094:
:Splat operator:
::You can turn an Array into an argument list with * (or splat) operator.
::<syntaxhighlight lang="ruby">def foo(a,b,c) p [a,b,c] end
 
args = [1,2,3]
Line 5,206 ⟶ 5,103:
:Syntax sugar:
::In Ruby, many operators are actually method calls.
::<syntaxhighlight lang="ruby"># return value substance
i = 3
p 1 + i #=> 4 1.+(i)
Line 5,220 ⟶ 5,117:
p "%2d %4s" % [1,"xyz"] #=> " 1 xyz" "%2d %4s".%([1,"xyz"])</syntaxhighlight>
::Method call which was displayed in the comment is usable actually.
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
// Rust has a lot of neat things you can do with functions: let's go over the basics first
fn no_args() {}
Line 5,313 ⟶ 5,209:
 
}</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<syntaxhighlight lang=Scala"scala">def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods
def myFunction0() = ???
myFunction0() // function invoked with empty parameter list
Line 5,381 ⟶ 5,276:
// No distinction between built-in functions and user-defined functions
// No distinction between subroutines and functions</syntaxhighlight>
 
=={{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 5,389 ⟶ 5,283:
* All parameters are positional.
 
* There are no differences between between calling built-in vs. user defined functions.<syntaxhighlight lang="seed7">env := environment; # Call a function that requires no arguments.
env := environment(); # Alternative possibility to call of a function with no arguments.
cmp := compare(i, j); # Call a function with a fixed number of arguments.</syntaxhighlight>
 
* There are no optional arguments, but a similar effect can be achieved with overloading.<syntaxhighlight lang="seed7">write(aFile, "asdf"); # Variant of write with a parameter to specify a file.
write("asdf"); # Variant of write which writes to the file OUT.</syntaxhighlight>
 
* Seed7 does not support functions with a variable number of arguments. But a function argument can be an array with as many values as you want:<syntaxhighlight lang="seed7">const func integer: sum (in array integer: intElems) is func
result
var integer: sum is 0;
Line 5,410 ⟶ 5,304:
t := sum([] (2, 3, 5, 7));</syntaxhighlight>
 
* Concatenation operators can be used to concatenate arguments. This solution is used to provide the write function:<syntaxhighlight lang="seed7">write("Nr: " <& num); # Use operators to concatenate arguments.</syntaxhighlight>
 
* The procedure ignore can be used to ignore a return value.<syntaxhighlight lang="seed7">ignore(getln(IN)); # Using a function in statement context (ignore the result).</syntaxhighlight>
 
* Call-by-name parameters use a function in first-class context. The function [http://seed7.sourceforge.net/examples/map.htm doMap] from the examples section of the Seed7 homepage uses a given expression to modify the elements of an array:<syntaxhighlight lang=seed7>seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x));</syntaxhighlight>
 
* Call-by-name parameters use a function in first-class context. The function [http://seed7.sourceforge.net/examples/map.htm doMap] from the examples section of the Seed7 homepage uses a given expression to modify the elements of an array:<syntaxhighlight lang="seed7">seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x));</syntaxhighlight>
=={{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:
Line 5,429 ⟶ 5,322:
 
* 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:
Line 5,446 ⟶ 5,339:
 
* A parameter is set to "" if nothing is specified
<syntaxhighlight lang="sensetalk">get ThreeArgFn("variable", (3, 4))
 
function ThreeArgFn arg1, arg2, arg3
Line 5,453 ⟶ 5,346:
 
* 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
 
Line 5,465 ⟶ 5,358:
* 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
Line 5,480 ⟶ 5,373:
 
SenseTalk also distinguishes between functions and subroutines, which it calls handlers:
<syntaxhighlight lang="sensetalk">CustomHandler 1, 2, 3
// Prints: 1 - 2 - 3
 
Line 5,488 ⟶ 5,381:
 
Subroutines can be called as a command, without storing the output
<syntaxhighlight lang="sensetalk">
MyCommand 1, "variable", (4, 5, 6)
 
Line 5,497 ⟶ 5,390:
 
Functions/subroutines can also be defined with the to, on or function keywords:
<syntaxhighlight lang="sensetalk">to MyFn args
...
end MyFn
Line 5,509 ⟶ 5,402:
end args
</syntaxhighlight>
 
=={{header|Sidef}}==
All functions in Sidef are first-class closures
<syntaxhighlight lang="ruby">foo(); # without arguments
foo(1, 2); # with two arguments
foo(args...); # with a variable number of arguments
Line 5,525 ⟶ 5,417:
Partial application is possible by using a curry function:
 
<syntaxhighlight lang="ruby">func curry(f, *args1) {
func (*args2) {
f(args1..., args2...);
Line 5,537 ⟶ 5,429:
var adder = curry(add, 1);
say adder(3); #=>4</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.</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="ssem">00110000000000100000000000000000 10. -12 to c
10110000000000000000000000000000 11. 13 to CI
11001111111111111111111111111111 12. -13
11001000000000000000000000000000 13. 19</syntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang=Swift"swift">// call a function with no args
noArgs()
 
Line 5,587 ⟶ 5,476:
// getting a bunch of return values, discarding second returned value
let (foo, _, baz) = returnSomeValues()</syntaxhighlight>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">aCallToACommandWithNoArguments
aCallToACommandWithOne argument
aCallToACommandWith arbitrarily many arguments
Line 5,597 ⟶ 5,485:
aCallToOneCommand [withTheResultOfAnother]</syntaxhighlight>
Tcl does differentiate between functions and other types of commands in expressions:
<syntaxhighlight lang="tcl">expr {func() + [cmd]}
expr {func(1,2,3} + [cmd a b c]}</syntaxhighlight>
However, there are no deep differences between the two: functions are translated into commands that are called in a particular namespace (thus <tt>foo()</tt> becomes <tt>tcl::mathfunc::foo</tt>).
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$
Line 5,640 ⟶ 5,526:
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:
 
<syntaxhighlight lang="sh">sayhello # Call a function in statement context with no arguments
multiply 3 4 # Call a function in statement context with two arguments</syntaxhighlight>
 
The shell does not support the use of named parameters. There is no lookahead in the shell, so functions cannot be called until their definition has been run.
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">'definitions/declarations
 
'Calling a function that requires no arguments
Line 5,797 ⟶ 5,680:
calling a subroutine does not require parentheses
deprecated use of parentheses</pre>
 
=={{header|WDTE}}==
<syntaxhighlight lang="wdte">let noargs => + 2 5;
noargs -- print;
 
Line 5,819 ⟶ 5,701:
# function.
(+ 3) 7 -- print;</syntaxhighlight>
 
=={{header|WebAssembly}}==
 
<syntaxhighlight lang="webassembly">(func $main (export "_start")
 
(local $result i32)
Line 5,853 ⟶ 5,734:
)
)</syntaxhighlight>
 
=={{header|Wren}}==
Wren distinguishes between functions and methods.
Line 5,881 ⟶ 5,761:
Here are some examples:
 
<syntaxhighlight lang="ecmascript">var f1 = Fn.new { System.print("Function 'f1' with no arguments called.") }
var f2 = Fn.new { |a, b|
System.print("Function 'f2' with 2 arguments called and passed %(a) & %(b).")
Line 5,925 ⟶ 5,805:
50
</pre>
 
=={{header|XLISP}}==
<syntaxhighlight lang="lisp">; call a function (procedure) with no arguments:
(foo)
 
Line 5,946 ⟶ 5,825:
(foo bar)
; nothing is done with the return value</syntaxhighlight>
 
=={{header|XSLT}}==
 
<syntaxhighlight lang="xml"><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
Line 6,227 ⟶ 6,105:
</xsl:stylesheet>
</syntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">
sub test(a, b, c) : print a, b, c : end sub
 
Line 6,248 ⟶ 6,125:
test$("1, 2, 3, 4, text, 6, 7, 8, \"include text\"")
print</syntaxhighlight>
=={{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:
<syntaxhighlight 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 6,264 ⟶ 6,174:
fcn{}.len.isType(self.fcn) //False, len is a Method</syntaxhighlight>
Partial application is done with the .fp* methods or the 'wrap keyword
<syntaxhighlight lang="zkl">
fcn(a,b,c).fp(1)() // call function with a always set to 1
fcn(a,b,c).fp1(2,3)() // call function with b & c always set to 2 & 3
Line 6,275 ⟶ 6,185:
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))</syntaxhighlight>
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module CallingProcs;
type
Line 6,334 ⟶ 6,243:
end CallingProcs.
</syntaxhighlight>
 
=={{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|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.
 
<syntaxhighlight lang="zxbasic">10 REM functions cannot be called in statement context
20 PRINT FN a(5): REM The function is used in first class context. Arguments are not named
30 PRINT FN b(): REM Here we call a function that has no arguments
Line 6,386 ⟶ 6,259:
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.</syntaxhighlight>
 
{{omit from|GUISS}}
10,327

edits