Call a function

From Rosetta Code
Revision as of 17:25, 4 July 2013 by rosettacode>Edward H (Added F# section.)
Task
Call a function
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to demonstrate the different syntax and semantics provided for calling a function. This may include:

  • Calling a function that requires no arguments
  • Calling a function with a fixed number of arguments
  • Calling a function with optional arguments
  • Calling a function with a variable number of arguments
  • Calling a function with named arguments
  • Using a function in statement context
  • Using a function in first-class context within an expression
  • Obtaining the return value of a function
  • Distinguishing built-in functions and user-defined functions
  • Distinguishing subroutines and functions
  • Stating whether arguments are passed by value or by reference
  • Is partial application possible and how

This task is not about defining functions.

ActionScript

<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</lang>

Ada

  • Ada provides two kinds of subroutines: procedures, without return values, and functions, with return values. The return values of procedures must be used by the callers. If you don't want do deal with the return value, call a procedure instead.
  • As a rule of thumb, an Ada compiler is free to pass arguments either by value or by reference. Parameters have a mode, however: either 'in' or 'out' or 'in out'. It is prohibited to write somthing to an 'in' parameter. The next language Standard, Ada 2012, will support functions with 'out' and 'in out' mode parameters, so far, only procedures could have parameters with non-'in' modes. So any of the following statements for Ada functions holds for Ada procedures as well.
  • There are no differences between between calling built-in vs. user defined functions.
  • Functions without parameters can be called by omitting the parameter list (no empty brackets!):<lang Ada>S: String := Ada.Text_IO.Get_Line;</lang>
  • Ada supports functions with optional parameters:<lang Ada>function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional

... A : Integer := F(12); B : Integer := F(12, 0); -- the same as A C : Integer := F(12, 1); -- something different</lang>

  • If the number of parameters of F where 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:<lang Ada>type Integer_Array is array (Positive range <>) of Integer;

function Sum(A: Integer_Array) return Integer is

  S: Integer := 0;

begin

  for I in A'Range loop
     S := S + A(I);
  end loop;
  return S;

end Sum; ... A := Sum((1,2,3)); -- A = 6 B := Sum((1,2,3,4)); -- B = 10</lang>

  • One can realize first-class functions by defining an access to a function as a parameter:<lang Ada>function H (Int: Integer;
           Fun: not null access function (X: Integer; Y: Integer)
             return Integer);
          return Integer;

...

X := H(A, F'Access) -- assuming X and A are Integers, and F is a function

                    -- taking two Integers and returning an Integer.</lang>
  • The caller is free to use either a positional parameters or named parameters, or a mixture of both (with positional parameters first) <lang Ada>Positional := H(A, F'Access);

Named  := H(Int => A, Fun => F'Access); Mixed  := H(A, Fun=>F'Access); </lang>

AutoHotkey

<lang AHK>; Call a function without arguments: f()

Call a function with a fixed number of arguments

f("string", var, 15.5)

Call a function with optional arguments

f("string", var, 15.5)

Call a function with a variable number of arguments

f("string", var, 15.5)

Call a function with named arguments
   ; AutoHotkey does not have named arguments. However, in v1.1+,
   ; we can pass an object to the function:

f({named: "string", otherName: var, thirdName: 15.5})

Use a function in statement context

f(1), f(2) ; What is statement context?

No first-class functions in AHK
Obtaining the return value of a function

varThatGetsReturnValue := f(1, "a")

Cannot distinguish built-in functions
Subroutines are called with GoSub; functions are called as above.
Subroutines cannot be passed variables
Stating whether arguments are passed by value or by reference
[v1.1.01+]
The IsByRef() function can be used to determine
whether the caller supplied a variable for a given ByRef parameter.
A variable cannot be passed by value to a byRef parameter. Instead, do this

f(tmp := varIdoNotWantChanged)

the function f will receive the value of varIdoNotWantChanged, but any
modifications will be made to the variable tmp.
Partial application is impossible.

</lang>

AWK

The awk interpreter reads the entire script prior to processing, so functions can be called from sections of code appearing before the definition.

<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

}</lang>

In awk, scalar values are passed by value, but arrays are passed by reference. Note that if a function has no arguments, then empty parentheses are required.

The awk extraction and reporting language does not support the use of named parameters.

C

<lang c>/* function with no argument */ f();

/* fix number of arguments */ g(1, 2, 3);

/* Optional arguments: err...

  Feel free to make sense of the following.  I can't. */

int op_arg(); int main() { op_arg(1); op_arg(1, 2); op_arg(1, 2, 3); return 0; } int op_arg(int a, int b) { printf("%d %d %d\n", a, b, (&b)[1]); return a; } /* end of sensible code */

/* Variadic function: how the args list is handled solely depends on the function */ void h(int a, ...) { va_list ap; va_start(ap); ... } /* call it as: (if you feed it something it doesn't expect, don't count on it working) */ h(1, 2, 3, 4, "abcd", (void*)0);

/* named arguments: no such thing */ /* statement context: is that a real phrase? */

/* as a first-class object (i.e. function pointer) */ printf("%p", f); /* that's the f() above */

/* return value */ double a = asin(1);

/* built-in functions: no such thing. Compiler may interally give special treatment

  to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */

/* subroutines: no such thing. You can goto places, but I doubt that counts. */

/* Scalar values are passed by value by default. However, arrays are passed by reference. */ /* Pointers *sort of* work like references, though. */</lang>

COBOL

<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</lang>

Erlang

<lang erlang> no_argument() one_argument( Arg ) optional_arguments( Arg, [{opt1, Opt1}, {another_opt, Another}] ) variable_arguments( [Arg1, Arg2 | Rest] ) names_arguments([{name1, Arg1}, {another_name, Another}] ) % Statement context? % First class context? Result = obtain_result( Arg1 ) % No way to distinguish builtin/user functions % Subroutines? % Arguments are passed by reference, but you can not change them. % Partial application is possible (a function returns a function that has one argument bound) </lang>

Icon and Unicon

Icon and Unicon have generalized procedures and syntax that are used to implement functions, subroutines and generators.

  • Procedures can return values or not and callers may use the returned values or not.
  • Procedures in Icon and Unicon are first class values and can be assigned to variables which can then be used to call procedures. This also facilitates some additional calling syntax.
  • Additionally, co-expressions are supported which allow for co-routine like transfers of control between two or more procedures. There are some differences in syntax for co-expression calls.
  • There are no differences between calling built-in vs. user defined functions
  • Named arguments is not natively supported; however, they can be supported using a user defined procedure as shown in Named parameters
  • Method calling is similar with some extended syntax
  • Arguments are basically passed by value or reference based on their type. Immutable values like strings, and numbers are passed by value. Mutable data types like structures are essentially references and although these are passed by value the effective behavior is like a call by reference.

For more information see Icon and Unicon Introduction on Rosetta

<lang Icon>procedure main() # demonstrate and describe function calling syntax and semantics

  # normal procedure/function calling
  f()                      # no arguments, also command context
  f(x)                     # fixed number of arguments
  f(x,h,w)                 # variable number of arguments (varargs)
  y := f(x)                # Obtaining the returned value of a function
  
  # procedures as first class values and string invocation 
  f!L                      # Alternate calling syntax using a list as args   
  (if \x then f else g)()  # call (f or g)()
  f := write               # assign a procedure
  f("Write is now called") # ... and call it
  "f"()                    # string invocation, procedure
  "-"(1)                   # string invocation, operator
  # Co-expressions
  
  f{e1,e2}                 # parallel evaluation co-expression call  
                           # equivalent to f([create e1, create e2]) 
  expr @ coexp             # transmission of a single value to a coexpression
  [e1,e2]@coexp            # ... of multiple values (list) to a coexpression 
  coexp(e1,e2)             # ... same as above but only in Unicon 
  # Other
  
  f("x:=",1,"y:=",2)       # named parameters (user defined)

end</lang>

F#

<lang fsharp>// No arguments noArgs()

// Fixed number of arguments oneArg x

// Optional arguments // In a normal function: optionalArgs <| Some(5) <| None // In a function taking a tuple: optionalArgsInTuple(Some(5), None) // In a function in a type: foo.optionalArgs 5;; // However, if you want to pass more than one paramter, the arguments must be // passed in a tuple: foo.optionalArgs(5, 6)

// Function with a variable number of arguments variableArgs 5 6 7 // etc...

// Named arguments can only be used in type methods taking a tuple. The // arguments can appear in any order. foo.namedArgs(x = 5, y = 6)

// Using a function in a statement for i = 0 to someFunc() do

   printfn "Something"

// Using a function in a first-class context funcArgs someFunc

// Obtaining a return value let x = someFunc()

// Built-in functions: do functions like (+) or (-) count?

// Parameters are normally passed by value (as shown in the previous examples), // but they can be passed by reference. // Passing by reference: refArgs &mutableVal

// Partial application example let add2 = (+) 2</lang>

J

A function in J is typically represented by a verb. Under the right circumstances other syntactic entities (nouns, adverbs, conjunctions) can represent functions, but let's focus on the typical case.

A verb, in J, typically supports two syntactic variants:

<lang j> verb noun

  noun verb noun</lang>

And a noun, in J, is an array.

An argument list can be represented by an array. Thus, when dealing with multiple arguments, a typical form is:

<lang j> function argumentList</lang>

Here, function is a verb and argumentList is a noun.

For example:

<lang j> sum(1,2,3)</lang>

Here sum is a verb and (1,2,3) is a noun.

Thus:

A function that requires no arguments can be simulated by calling a function with empty argument list: <lang j>f</lang> 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. <lang j>f 'one argument'</lang>and <lang j>'this example has two arguments' f 'the other argument'</lang> 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: <lang j> f 1,2,3,4,5</lang> and here's a boxed example with five arguments: <lang j>f (<1),(<2),(<3),(<4),(<5) </lang> Note that the last set of parenthesis is unnecessary <lang j>f (<1),(<2),(<3),(<4),<5</lang> Note also that J offers some syntactic sugar for this kind of list <lang j>f 1; 2; 3; 4; <5</lang>. 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). <lang j>f 1; 2; 3; 4; 5</lang>

A function with named arguments can be accomplished by calling a function with the names of the arguments. <lang j>f 'george';'tom';'howard'</lang> 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: <lang j>1 2 3 f 'george';'tom';'howard'</lang> 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:<lang j> obj=: conew'blank'

  george__obj=: 1
  tom__obj=: 2
  howard__obj=: 3
  f obj
  coerase obj</lang>  Name/value pairs can also be used for this purpose and can be implemented in various ways, including passing names followed by values <lang j>f 'george';1;'tom';2;'howard';3</lang> and passing a structure of pairs <lang j>f ('george';1),('tom';2),:(howard';3)</lang>  Or, for example, the pairs could be individually boxed:  <lang j>f ('george';1);('tom';2);<howard';3</lang>

Using a function in command context is no different from using a function in any other context, in J. Using a function in first class context within an expression is no different from using a function in any other context, in J.

Obtaining the return value of a function is no different from using a function in j. For example, here we add 1 to the result of a function: <lang j>1 + f 2</lang>

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 subroutines nor functions. Instead, J defines verbs, adverbs, and conjunctions which for the purpose of this task are treated as functions.

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.

<lang JavaScript>var foo = function() { return arguments.length }; foo() // 0 foo(1, 2, 3) // 3</lang>

Neither optional (see above) nor named arguments are supported, though the latter (and the inverse of the former) may be simulated with the use of a helper object to be queried for the existence and/or values of relevant keys. Seriously, what is "statement context"?

JavaScript functions are first-class citizens; they can be stored in variables (see above) and passed as arguments. <lang JavaScript>var squares = [1, 2, 3].map(function (n) { return n * n }); // [1, 4, 9]</lang>

Naturally, they can also be returned, thus partial application is supported. <lang JavaScript> var make_adder = function(m) {

   return function(n) { return m + n }

}; var add42 = make_adder(42); add42(10) // 52</lang>

Calling a user-defined function's toString() method returns its source verbatim; that the implementation is elided for built-ins provides a mechanism for distinguishing between the two.

<lang JavaScript>foo.toString() "function () { return arguments.length }" alert.toString() "function alert() { [native code] }"</lang>

Arguments are passed by value, but the members of collections are essentially passed by reference and thus propagate modification. <lang JavaScript>var mutate = function(victim) {

   victim[0] = null;
   victim = 42;

}; var foo = [1, 2, 3]; mutate(foo) // foo is now [null, 2, 3], not 42</lang>

LFE

Calling a function that requires no arguments:

In some module, define the following: <lang lisp> (defun my-func()

 (: io format '"I get called with NOTHING!~n"))

</lang>

Then you use it like so (depending upon how you import it): <lang lisp> > (my-func) I get called with NOTHING! ok </lang>

Calling a function with a fixed number of arguments: In some module, define the following: <lang lisp> (defun my-func(a b)

 (: io format '"I got called with ~p and ~p~n" (list a b)))

</lang>

Then you use it like so: <lang lisp> > (my-func '"bread" '"cheese") I got called with "bread" and "cheese" ok </lang>

Calling a function with optional arguments or calling a function with a variable number of arguments:

  • Arguments are fixed in LFE/Erlang functions.
  • One can have a dictionary, record, or list be the function argument, and use that to achieve something like variable/optional (and named) arguments.
  • One can define multiple functions so that it appears that one is calling a function with optional or a variable number of arguments:

<lang lisp> (defmodule args

 (export all))

(defun my-func ()

 (my-func () () ()))

(defun my-func (a)

 (my-func a () ()))

(defun my-func (a b)

 (my-func a b ()))

(defun my-func (a b c)

 (: io format '"~p ~p ~p~n" (list a b c)))

</lang>

Here is some example usage: <lang lisp> > (slurp '"args.lfe")

  1. (ok args)

> (my-func) [] [] [] ok > (my-func '"apple") "apple" [] [] ok > (my-func '"apple" '"banana") "apple" "banana" [] ok > (my-func '"apple" '"banana" '"cranberry") "apple" "banana" "cranberry" ok > (my-func '"apple" '"banana" '"cranberry" '"bad arg") exception error: #(unbound_func #(my-func 4)) </lang>

Calling a function with named arguments:

  • LFE/Erlang doesn't support named arguments, per se.
  • However, by using atoms in function argument patterns (a fairly common pattern), one can achieve similar effects.
  • One may also use records or dicts as arguments to achieve similar effects.


Using a function in statement context: <lang lisp> ...

 (cond ((== count limit) (hit-limit-func arg-1 arg-2))
       ((/= count limit) (keep-going-func count)))
 ...

</lang>

Using a function in first-class context within an expression:

From the LFE REPL: <lang lisp> > (>= 0.5 (: math sin 0.5)) true </lang>

Obtaining the return value of a function:

There are many, many ways to assign function outputs to variables in LFE. One fairly standard way is with the (let ...) form: <lang lisp> (let ((x (: math sin 0.5)))

 ...)

</lang>

Distinguishing built-in functions and user-defined functions:

  • There is no distinction made in LFE/Erlang between functions that are built-in and those that are not.
  • "Built-in" for LFE/Erlang usually can be figured out: if a function has the module name erlang, e.g., (: erlang list_to_integer ... )</cod>, then it's built-in.
  • Most of the functions that come with LFE/Erlang are not even in the erlang module, but exist in other modules (e.g., io, math, etc.) and in OTP.
  • One uses user/third-party modules in exactly the same way as one uses built-ins and modules that come with the Erlang distribution.


Distinguishing subroutines and functions:

  • One commonly made distinction between functions and subroutines is that functions return a value (or reference, etc.) and subroutines do not.
  • By this definition, LFE/Erlang does not support the concept of a subroutine; all functions return something.


Stating whether arguments are passed by value or by reference:

  • Arguments and returns values are passed by reference in LFE/Erlang.


Is partial application possible?

  • Not explicitly.
  • However, one can use lambdas to achieve the same effect.


Lua

<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 fixed(1, 2, 3, 4, 5) --> 1 2 3

-- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values. function vararg (...) print(...) end vararg(1, 2, 3, 4, 5) -- 1 2 3 4 5

-- Lua also allows dropping the parentheses if table or string literals are used as the sole argument print "some string" print { foo = "bar" } -- also serves as a form of named arguments

-- First-class functions in expression context print(("this is backwards uppercase"):gsub("%w+", function (s) return s:upper():reverse() end))

-- Functions can return multiple values (including none), which can be counted via select() local iter, obj, start = ipairs { 1, 2, 3 } print(select("#", (function () end)())) --> 0 print(select("#", unpack { 1, 2, 3, 4 })) --> 4

-- Partial application function prefix (pre)

   return function (suf) return pre .. suf end

end

local prefixed = prefix "foo" print(prefixed "bar", prefixed "baz", prefixed "quux")

-- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference. -- There is no separate notion of subroutines -- Built-in functions are not easily distinguishable from user-defined functions </lang>

Mathematica

Calling a function that requires no arguments: <lang Mathematica>f[]</lang>

Calling a function with a fixed number of arguments: <lang Mathematica>f[1,2]</lang>

Calling a function with optional arguments: <lang Mathematica>f[1,Option1->True]</lang>

Calling a function with a variable number of arguments: <lang Mathematica>f[1,Option1->True] f[1,Option1->True,Option2->False]</lang>

Calling a function with named arguments: <lang Mathematica>f[Option1->True,Option2->False]</lang>

Using a function in statement context: <lang Mathematica>f[1,2];f[2,3]</lang>

Using a function in first-class context within an expression: <lang Mathematica>(#^2)&[3];</lang>

The return value of a function can be formally extracted using Return[] Built-in functions names by convention start with a capital letter. No formal distinction between subroutines and functions. Arguments can be passed by value or by reference.

MATLAB / Octave

<lang Matlab>

   % Calling a function that requires no arguments
      function a=foo(); 
        a=4;
      end;
      x = foo(); 
   % Calling a function with a fixed number of arguments
      function foo(a,b,c); 
        %% function definition;
      end;
      foo(x,y,z); 
   % Calling a function with optional arguments
      function foo(a,b,c); 

if nargin<2, b=0; end; if nargin<3, c=0; end;

        %% function definition;
      end;
      foo(x,y); 
   % Calling a function with a variable number of arguments
      function foo(varargin); 

for k=1:length(varargin)

           arg{k} = varargin{k};	
      end;
      foo(x,y); 
   % Calling a function with named arguments

%% does not apply

   % Using a function in statement context

%% does not apply

   % Using a function in first-class context within an expression
   % Obtaining the return value of a function
      function [a,b]=foo(); 
        a=4;
        b='result string';
      end;
      [x,y] = foo(); 
   % Distinguishing built-in functions and user-defined functions

fun = 'foo'; if (exist(fun,'builtin'))

		printf('function %s is a builtin\n');
       elseif (exist(fun,'file'))
		printf('function %s is user-defined\n');
       elseif (exist(fun,'var'))
		printf('function %s is a variable\n');
       else 
		printf('%s is not a function or variable.\n');
       end
   % Distinguishing subroutines and functions
       % there are only scripts and functions, any function declaration starts with the keyword function, otherwise it is a script that runs in the workspace
   % Stating whether arguments are passed by value or by reference 
     % arguments are passed by value, however Matlab has delayed evaluation, such that a copy of large data structures are done only when an element is written to.  

</lang>

OCaml

  • Calling a function that requires no arguments:

<lang ocaml>f ()</lang>

(In fact it is impossible to call a function without arguments, when there are no particular arguments we provide the type unit which is a type that has only one possible value. This type is mainly made for this use.)

  • Calling a function with a fixed number of arguments:

<lang ocaml>f 1 2 3</lang>

  • Calling a function with optional arguments:

For a function that has this signature:

<lang ocaml>val f : ?a:int -> int -> unit</lang>

here is how to call it with or without the first argument omited:

<lang ocaml>f 10 f ~a:6 10</lang>

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 unit:

<lang ocaml>g () g ~b:1.0 ()</lang>

  • Calling a function with a variable number of arguments:

This is not possible. The strong OCaml type system does not allow this. The OCaml programmer will instead provide the variable number of arguments in a list, an array, an enumeration, a set or any structure of this kind. (But if we really need this for a good reason, it is still possible to use a hack, like it has been done for the function Printf.printf.)

  • Calling a function with named arguments:

Named arguments are called labels.

<lang ocaml>f ~arg:3</lang>

If a variable has the same name than the label we can use this simpler syntax:

<lang ocaml>let arg = 3 in f ~arg</lang>

  • Using a function in statement context:

<lang ocaml>(* TODO *)</lang>

  • Using a function in first-class context within an expression:

functions in OCaml are first-class citizen.

  • Obtaining the return value of a function:

<lang ocaml>let ret = f () let a, b, c = f () (* if there are several returned values given as a tuple *) let _ = f () (* if we want to ignore the returned value *) let v, _ = f () (* if we want to ignore one of the returned value *)</lang>

  • Distinguishing built-in functions and user-defined functions:

There is no difference.

  • Distinguishing subroutines and functions:

OCaml only provides functions.

  • Stating whether arguments are passed by value or by reference:

OCaml arguments are always passed by reference. OCaml is an impure functional language, for immutable variables there is no difference if the argument is passed by value or by reference, but for mutable variables the programmer should know that a function is able to modify it.

  • How to use partial application:

Just apply less arguments than the total number of arguments.

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.

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.

Optional arguments can be skipped, leaving commas in place. Trailing commas can be dropped.

Functions can be used when statements would be expected without change. <lang parigp>f(); \\ zero arguments sin(Pi/2); \\ fixed number of arguments Str("gg", 1, "hh"); \\ variable number of arguments (x->x^2)(3); \\ first-class x = sin(0); \\ get function value</lang>

Built-in functions are like user-defined functions in current versions. In older versions built-in functions cannot be passed as closures.

Most arguments are passed by reference. Some built-in functions accept arguments (e.g., flags) that are not GENs; 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".

Perl 6

Fundamentally, nearly everything you do in Perl 6 is a function call if you look hard enough. At the lowest level, a function call merely requires a reference to any kind of invokable object, and a call to its postcircumfix:<( )> method. However, there are various forms of sugar and indirection that you can use to express these function calls differently. In particular, operators are all just sugar for function calls.

Calling a function that requires no arguments:

<lang perl6>foo # as list operator foo() # as function foo.() # as function, explicit postfix form $ref() # as object invocation $ref.() # as object invocation, explicit postfix &foo() # as object invocation &foo.() # as object invocation, explicit postfix

($name)() # as symbolic ref</lang>

Calling a function with exactly one argument:

<lang perl6>foo 1 # as list operator foo(1) # as named function foo.(1) # as named function, explicit postfix $ref(1) # as object invocation (must be hard ref) $ref.(1) # as object invocation, explicit postfix 1.$foo # as pseudo-method meaning $foo(1) (hard ref only) 1.$foo() # as pseudo-method meaning $foo(1) (hard ref only) 1.&foo # as pseudo-method meaning &foo(1) (is hard foo) 1.&foo() # as pseudo-method meaning &foo(1) (is hard foo) 1.foo # as method via dispatcher 1.foo() # as method via dispatcher 1."$name"() # as method via dispatcher, symbolic +1 # as operator to prefix:<+> function</lang>

Method calls are included here because they do eventually dispatch to a true function via a dispatcher. However, the dispatcher in question is not going to dispatch to the same set of functions that a function call of that name would invoke. That's why there's a dispatcher, after all. Methods are declared with a different keyword, method, in Perl 6, but all that does is install the actual function into a metaclass. Once it's there, it's merely a function that expects its first argument to be the invocant object. Hence we feel justified in including method call syntax as a form of indirect function call.

Operators like + also go through a dispatcher, but in this case it is multiply dispatched to all lexically scoped candidates for the function. Hence the candidate list is bound early, and the function itself can be bound early if the type is known. Perl 6 maintains a clear distinction between early-bound linguistic constructs that force Perlish semantics, and late-bound OO dispatch that puts the objects and/or classes in charge of semantics. (In any case, &foo, though being a hard ref to the function named "foo", may actually be a ref to a dispatcher to a list of candidates that, when called, makes all the candidates behave as a single unit.)

Calling a function with exactly two arguments:

<lang perl6>foo 1,2 # as list operator foo(1,2) # as named function foo.(1,2) # as named function, explicit postfix $ref(1,2) # as object invocation (must be hard ref) $ref.(1,2) # as object invocation, explicit postfix 1.$foo: 2 # as pseudo-method meaning $foo(1,2) (hard ref only) 1.$foo(2) # as pseudo-method meaning $foo(1,2) (hard ref only) 1.&foo: 2 # as pseudo-method meaning &foo(1,2) (is hard foo) 1.&foo(2) # as pseudo-method meaning &foo(1,2) (is hard foo) 1.foo: 2 # as method via dispatcher 1.foo(2) # as method via dispatcher 1."$name"(2) # as method via dispatcher, symbolic 1 + 2 # as operator to infix:<+> function</lang>

Optional arguments don't look any different from normal arguments. The optionality is all on the binding end.

Calling a function with a variable number of arguments (varargs):

<lang perl6>foo @args # as list operator foo(@args) # as named function foo.(@args) # as named function, explicit postfix $ref(@args) # as object invocation (must be hard ref) $ref.(@args) # as object invocation, explicit postfix 1.$foo: @args # as pseudo-method meaning $foo(1,@args) (hard ref) 1.$foo(@args) # as pseudo-method meaning $foo(1,@args) (hard ref) 1.&foo: @args # as pseudo-method meaning &foo(1,@args) 1.&foo(@args) # as pseudo-method meaning &foo(1,@args) 1.foo: @args # as method via dispatcher 1.foo(@args) # as method via dispatcher 1."$name"(@args) # as method via dispatcher, symbolic @args X @blargs # as list infix operator to infix:<X></lang> Note: whether a function may actually be called with a variable number of arguments depends entirely on whether a signature accepts a list at that position in the argument list, but describing that is not the purpose of this task. Suffice to say that we assume here that the foo function is declared with a signature of the form (*@params). The calls above might be interpreted as having a single array argument if the signature indicates a normal parameter instead of a variadic one. What you cannot do in Perl 6 (unlike Perl 5) is pass an array as several fixed arguments. By default it must either represent a single argument, or be part of a variadic list. You can force the extra level of argument list interpolation using a prefix | however:

<lang perl6>my @args = 1,2,3; foo(|@args); # equivalent to foo(1,2,3)</lang>

Calling a function with named arguments:

<lang perl6>foo :a, :b(4), :!c, d => "stuff" foo(:a, :b(4), :!c, d => "stuff")</lang>

...and so on. Operators may also be called with named arguments, but only colon adverbials are allowed:

<lang perl6>1 + 1 :a :b(4) :!c :d("stuff") # calls infix:<+>(1,1,:a, :b(4), :!c, d => "stuff")</lang>

Using a function in statement context:

<lang perl6>foo(); bar(); baz(); # evaluate for side effects</lang>

Using a function in first class context within an expression:

<lang perl6>1 / find-a-func(1,2,3)(4,5,6) ** 2;</lang>

Obtaining the return value of a function:

<lang perl6>my $result = somefunc(1,2,3) + 2;</lang>

There is no difference between calling builtins and user-defined functions and operators (or even control stuctures). This was a major design goal of Perl 6, and apart from a very few low-level primitives, all of Perl 6 can be written in Perl 6.

There is no difference between calling subroutines and functions in Perl 6, other than that calling a function in void context that has no side effects is likely to get you a "Useless use of..." warning. And, of course, the fact that pure functions can participate in more optimizations such as constant folding.

By default, arguments are passed readonly, which allows the implementation to decide whether pass-by-reference or pass-by-value is more efficient on a case-by-case basis. Explicit lvalue, reference, or copy semantics may be requested on a parameter-by-parameter basis, and the entire argument list may be processed raw if that level of control is needed.

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): <lang PicoLisp>(foo) (bar 1 'arg 2 'mumble)</lang> 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): <lang PicoLisp>(mapc println Lst) # The value of 'printlin' is a number (apply '((A B C) (foo (+ A (* B C)))) (3 5 7)) # A list is passed</lang> Any argument to a function may be evaluated or not, depending on the function. For example, 'setq' evaluates every second argument <lang PicoLisp>(setq A (+ 3 4) B (* 3 4))</lang> i.e. the first argument 'A' is not evaluated, the second evaluates to 7, 'B' is not evaluated, then the fourth evaluates to 12.

Python

<lang python>def no_args():

   pass
  1. call

no_args()

def fixed_args(x, y):

   print('x=%r, y=%r' % (x, y))
  1. call

fixed_args(1, 2) # x=1, y=2

def opt_args(x=1):

   print(x)
  1. calls

opt_args() # 1 opt_args(3.141) # 3.141

def var_args(*v):

   print(v)
  1. calls

var_args(1, 2, 3) # (1, 2, 3) var_args(1, (2,3)) # (1, (2, 3)) var_args() # ()

    1. Named arguments

fixed_args(y=2, x=1) # x=1, y=2

    1. As a statement

if 1:

   no_args()
    1. First-class within an expression

assert no_args() is None

def return_something():

   return 1

x = return_something()

def is_builtin(x): print(x.__name__ in dir(__builtins__))

  1. calls

is_builtin(pow) # True is_builtin(is_builtin) # False

    1. A subroutine is merely a function that has no explicit
    2. return statement and will return None.
    1. Python uses "Call by Object Reference".
    2. See, for example, http://www.python-course.eu/passing_arguments.php
    1. For partial function application see:
    2. http://rosettacode.org/wiki/Partial_function_application#Python</lang>

Racket

<lang Racket>

  1. lang racket
Calling a function that requires no arguments

(foo)

Calling a function with a fixed number of arguments

(foo 1 2 3)

Calling a function with optional arguments
Calling a function with a variable number of arguments

(foo 1 2 3) ; same in both cases

Calling a function with named arguments

(foo 1 2 #:x 3) ; using #:keywords for the names

Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
-> Makes no sense for Racket, as well as most other functional PLs
Distinguishing built-in functions and user-defined functions

(primitive? foo)

but this is mostly useless, since most of Racket is implemented in
itself
Distinguishing subroutines and functions
-> No difference, though `!' is an idiomatic suffix for names of
side-effect functions, and they usually return (void)
Stating whether arguments are passed by value or by reference
-> Always by value, but it's possible to implement languages with
other argument passing styles, including passing arguments by
reference (eg, there is "#lang algol60")
Is partial application possible and how

(curry foo 1 2)  ; later apply this on 3 (λ(x) (foo 1 2 x)) ; a direct way of doing the same </lang>

REXX

<lang rexx>/*REXX program to demonstrate various methods of calling a REXX function*/ /*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function that REQUIRES no arguments.                     │
 │                                                                    │
 │ In the REXX language, there is no way to require the caller to not │
 │ pass arguments, but the programmer can check if any arguments were │
 │ (or weren't) passed.                                               │
 └────────────────────────────────────────────────────────────────────┘*/

yr=yearFunc() say 'year=' yr exit

yearFunc: procedure if arg()\==0 then call sayErr "SomeFunc function won't accept arguments." return left(date('Sorted'),3) /*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function with a fixed number of arguments.               │
 │                                                                    │
 │ I take this to mean that the function requires a fixed number of   │
 │ arguments.   As above, REXX doesn't enforce calling (or invoking)  │
 │ a (any) function with a certain number of arguments,  but the      │
 │ programmer can check if the correct number of arguments have been  │
 │ specified (or not).                                                │
 └────────────────────────────────────────────────────────────────────┘*/

ggg=FourFunc(12,abc,6+q,zz%2,'da 5th disagreement') say 'ggg squared=' ggg**2 exit

FourFunc: procedure; parse arg a1,a2,a3; a4=arg(4) /*another way get a4*/

if arg()\==4 then do

                 call sayErr "FourFunc function requires 4 arguments,"
                 call sayErr "but instead it found" arg() 'arguments.'
                 exit 13
                 end

return a1+a2+a3+a4 /*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function with optional arguments.                        │
 │                                                                    │
 │ Note that not passing an argument isn't the same as passing a null │
 │ argument  (a REXX variable whose value is length zero).            │
 └────────────────────────────────────────────────────────────────────┘*/

x=12; w=x/2; y=x**2; z=x//7 /* z is x modulo seven.*/ say 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass 5 args, 4th is null*/ exit

SumIt: procedure; sum=0

 do j=1 for arg()
 if arg(j,'E') then sum=sum+arg(j)  /*the Jth arg may have been omitted*/
 end

return sum /*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function with a variable number of arguments.            │
 │                                                                    │
 │ This situation isn't any different then the previous example.      │
 │ It's up to the programmer to code how to utilize the arguments.    │
 └────────────────────────────────────────────────────────────────────┘*/

/*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function with named arguments.                           │
 │                                                                    │
 │ REXX allows almost anything to be passed, so the following is one  │
 │ way this can be accomplished.                                      │
 └────────────────────────────────────────────────────────────────────┘*/

what=parserFunc('name=Luna',"gravity=.1654",'moon=yes') say 'name=' common.name gr=common.gr say 'gravity=' gr exit

parseFunc: procedure expose common.

     do j=1 for arg()
     parse var arg(j) name '=' val
     upper name
     call value 'COMMON.'name,val
     end

return arg() /*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function in statement context.                           │
 │                                                                    │
 │ REXX allows functions to be called (invoked) two ways, the first   │
 │ example (above) is calling a function in statement context.        │
 └────────────────────────────────────────────────────────────────────┘*/

/*┌────────────────────────────────────────────────────────────────────┐

 │ Calling a function in within an expression.                        │
 │                                                                    │
 │ This is a variant of the first example.                            │
 └────────────────────────────────────────────────────────────────────┘*/

yr=yearFunc()+20 say 'two decades from now, the year will be:' yr exit /*┌────────────────────────────────────────────────────────────────────┐

 │ Obtaining the return value of a function.                          │
 │                                                                    │
 │ There are two ways to get the (return) value of a function.        │
 └────────────────────────────────────────────────────────────────────┘*/

currYear=yearFunc() say 'the current year is' currYear

call yearFunc say 'the current year is' result /*┌────────────────────────────────────────────────────────────────────┐

 │ Distinguishing built-in functions and user-defined functions.      │
 │                                                                    │
 │ One objective of the REXX language is to allow the user to use any │
 │ function (or subroutine) name whether or not there is a built-in   │
 │ function with the same name  (there isn't a penality for this).    │
 └────────────────────────────────────────────────────────────────────┘*/

qqq=date() /*number of real dates that Bob was on. */ say "Bob's been out" qqq 'times.' www='DATE'('USA') /*returns date in format mm/dd/yyy */ exit /*any function in quotes is external. */

date: return 4 /*┌────────────────────────────────────────────────────────────────────┐

 │ Distinguishing subroutines and functions.                          │
 │                                                                    │
 │ There is no programatic difference between subroutines and         │
 │ functions if the subroutine returns a value  (which effectively    │
 │ makes it a function).   REXX allows you to call a function as if   │
 │ it were a subroutine.                                              │
 └────────────────────────────────────────────────────────────────────┘*/

/*┌────────────────────────────────────────────────────────────────────┐

 │ In REXX, all arguments are passed by value, never by name,  but it │
 │ is possible to accomplish this if the variable's name is passed    │
 │ and the subroutine/function could use the built-in-function VALUE  │
 │ to retrieve the variable's value.                                  │
 └────────────────────────────────────────────────────────────────────┘*/

/*┌────────────────────────────────────────────────────────────────────┐

 │ In the REXX language, partial application is possible, depending   │
 │ how partial application is defined; I prefer the 1st definition (as│
 │ (as per the "discussion" for "Partial Function Application" task:  │
 │   1.  The "syntactic sugar" that allows one to write (some examples│
 │       are:      map (f 7 9)  [1..9]                                │
 │        or:      map(f(7,_,9),{1,...,9})                            │
 └────────────────────────────────────────────────────────────────────┘*/</lang>

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.
  • Seed7 supports call-by-value, call-by-reference, and call-by-name parameters. Programmers are free to specify the desired parameter passing mechanism. The most used parameter passing mechanism is 'in'. Depending on the type 'in' specifies call-by-value (for integer, float, ...) or call-by-reference (for string, array, ...). It is prohibited to write something to an 'in' parameter.
  • All parameters are positional.
  • There are no differences between between calling built-in vs. user defined functions.<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.</lang>

  • There are no optional arguments, but a similar effect can be achieved with overloading.<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.</lang>

  • 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:<lang seed7>const func integer: sum (in array integer: intElems) is func
 result
   var integer: sum is 0;
 local
   var integer: element is 0;
 begin
   for element range intElems do
     sum +:= element;
   end for;
 end func;

s := sum([] (1, 2, 3)); # Use an aggregate to generate an array. t := sum([] (2, 3, 5, 7));</lang>

  • Concatenation operators can be used to concatenate arguments. This solution is used to provide the write function:<lang seed7>write("Nr: " <& num); # Use operators to concatenate arguments.</lang>
  • The procedure ignore can be used to ignore a return value.<lang seed7>ignore(getln(IN)); # Using a function in statement context (ignore the result).</lang>
  • Call-by-name parameters use a function in first-class context. The function doMap from the examples section of the Seed7 homepage uses a given expression to modify the elements of an array:<lang seed7>seq := doMap([](1, 2, 4, 6, 10, 12, 16), x, succ(x));</lang>

Smalltalk

Where f is a closure and arguments is an array of values for f to operate on. <lang smalltalk>f valueWithArguments: arguments.</lang>

Tcl

<lang tcl>aCallToACommandWithNoArguments aCallToACommandWithOne argument aCallToACommandWith arbitrarily many arguments aCallToACommandWith {*}$manyArgumentsComingFromAListInAVariable aCallToACommandWith -oneNamed argument -andAnother namedArgument aCallToACommandWith theNameOfAnotherCommand aCallToOneCommand [withTheResultOfAnother]</lang> Tcl does differentiate between functions and other types of commands in expressions: <lang tcl>expr {func() + [cmd]} expr {func(1,2,3} + [cmd a b c]}</lang> However, there are no deep differences between the two: functions are translated into commands that are called in a particular namespace (thus foo() becomes tcl::mathfunc::foo). 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).

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:

<lang sh>sayhello # Call a function in statement context with no arguments multiply 3 4 # Call a function in statement context with two arguments</lang>

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.

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.

<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 40 REM subroutines cannot be passed parameters, however variables are global 50 LET n=1: REM This variable will be visible to the called subroutine 60 GO SUB 1000: REM subroutines are called by line number and do not have names 70 REM subroutines do not return a value, but we can see any variables it defined 80 REM subroutines cannot be used in first class context 90 REM builtin functions are used in first class context, and do not need the FN keyword prefix 100 PRINT SIN(50): REM here we pass a parameter to a builtin function 110 PRINT RND(): REM here we use a builtin function without parameters 120 RANDOMIZE: REM statements are not functions and cannot be used in first class context.</lang>