Function prototype

From Rosetta Code
Revision as of 22:23, 10 March 2013 by rosettacode>Markhobley (omissions)
Task
Function prototype
You are encouraged to solve this task according to the task description, using any language you may know.

Some languages provide the facility to declare functions and subroutines through the use of function prototyping. The task is to demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:

  • An explanation of any placement restrictions for prototype declarations
  • A prototype declaration for a function that does not require arguments
  • A prototype declaration for a function that requires two arguments
  • A prototype declaration for a function that utilizes varargs
  • A prototype declaration for a function that utilizes optional arguments
  • A prototype declaration for a function that utilizes named parameters
  • Example of prototype declarations for subroutines or procedures (if these differ from functions)
  • An explanation and example of any special forms of prototyping not covered by the above

Languages that do not provide function prototyping facilities should be omitted from this task.

Ada

  • Prototypes must be an exact copy of everything prior to the "is" statement for a function or procedure.
  • All prototypes must appear in a declarative section, ie: before a "begin" statement.
  • For a main program, prototypes are only necessary if a function call appears in the source before the function definition.
  • For a with'd file, prototypes must appear as part of the specification(.ads) file, and do not appear in the body file(.adb).

<lang Ada>function noargs return Integer; function twoargs (a, b : Integer) return Integer; -- varargs do not exist function optionalargs (a, b : Integer := 0) return Integer; -- all parameters are always named, only calling by name differs procedure dostuff (a : Integer);</lang> Other Prototyping: Since pointers are not generic in Ada, a type must be defined before one can have a pointer to that type, thus for making linked-list type semantics another trivial prototyping exists: <lang Ada>type Box; -- tell Ada a box exists (undefined yet) type accBox is access Box; -- define a pointer to a box type Box is record -- later define what a box is

  next : accBox; --  including that a box holds access to other boxes

end record;</lang>

C

Function prototypes are typically included in a header file at the beginning of a source file prior to functional code. However, this is not enforced by a compiler.

<lang c>int noargs(); /* Declare a function with no arguments that returns an integer */ int twoargs(int a,int b); /* Declare a function with no arguments that returns an integer */ int twoargs(int ,int); /* Parameter names are optional in a prototype definition */ int anyargs(...); /* An ellipsis can be used to declare a function that accepts varargs */ int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */</lang>

Common Lisp

The lambda list is part of the function definition. It describes the arguments to a function.

<lang lisp>;; An empty lambda list () takes 0 parameters. (defun 0args ()

 (format t "Called 0args~%"))
This lambda list (a b) takes 2 parameters.

(defun 2args (a b)

 (format t "Called 2args with ~A and ~A~%" a b))
Local variables from lambda lists may have declarations.
This function takes 2 arguments, which must be integers.

(defun 2ints (i j)

 (declare (type integer i j))
 (/ (+ i j) 2))</lang>

When a program calls a function, Common Lisp uses the lambda list to check the number and type of arguments. Calls like (0args "extra arg"), (2args) and (2ints 3.0 4/5) would cause errors.

The lambda list has several more features.

<lang lisp>;; Rest parameter, for variadic functions: r is a list of arguments. (a b &rest r)

Optional parameter
i defaults to 3, (f 1 2) is same as (f 1 2 3).

(a b &optional (i 3))

Keyword parameters
(f 1 2
c 3 :d 4) is same as (f 1 2 :d 4 :c 3).

(a b &key c d)</lang>

D

Beside function prototypes similar to the ones available in C (plus templates, D-style varargs), you can define class method prototypes in abstract classes and interfaces. The exact rules for this are best explained by the documentation <lang d>/// Declare a function with no arguments that returns an integer. int noArgs();

/// Declare a function with no arguments that returns an integer. int twoArgs(int a, int b);

/// Parameter names are optional in a prototype definition. int twoArgs2(int, int);

/// An ellipsis can be used to declare a function that accepts /// C-style varargs. int anyArgs(...);

/// One mandatory integer argument followed by C-style varargs. int atLeastOneArg(int, ...);

/// Declare a function that accepts any number of integers. void anyInts(int[] a...);

/// Declare a function that accepts D-style varargs. void anyArgs2(TArgs...)(TArgs args);

/// Declare a function that accepts two or more D-style varargs. void anyArgs3(TArgs...)(TArgs args) if (TArgs.length > 2);

/// Currently D doesn't support named arguments.

/// One implementation. int twoArgs(int a, int b) {

   return a + b;

}

interface SomeInterface {

   void foo();
   void foo(int, int);
   // Varargs
   void foo(...); // C-style.
   void foo(int[] a...);
   void bar(T...)(T args); // D-style.
   // Optional arguments are only supported if a default is provided,
   // the default arg(s) has/have to be at the end of the args list.
   void foo(int a, int b = 10);

}

void main() {}</lang>

PARI/GP

GP does not use function prototypes.

PARI uses C prototypes. Additionally, gp2c parser codes are essentially function prototypes. They must be placed in the file called by gp2c, not in a file included by it, and they must appear as a GP; comment. For a function

<lang c>long foo(GEN a, GEN b)</lang> which takes two (required) t_INT arguments, returns a small integer (a C long) and appears as bar to the gp interpreter, the following command would be used: <lang c>/* GP;install("foo","LGG","bar","./filename.gp.so");

  • /</lang>

If its arguments were optional it could be coded as <lang c>/* GP;install("foo","LDGDG","bar","./filename.gp.so");

  • /</lang>

although other parser codes are possible; this one sends NULL if the arguments are omitted.

A code like <lang c>/* GP;install("foo","s*","bar","./filename.gp.so");

  • /</lang>

can be used to take a variable (0 or more) number of arguments. Note that the return type in this case is implicitly GEN

Other special forms are described in the User's Guide to the PARI library, section 5.7.3.

Perl

The perl scripting language allows prototypes to be checked during JIT compilation. Prototypes should be placed before subroutine definitions, declarations, or anonymous subroutines. The sigil special symbols act as argument type placeholders.

<lang perl>sub noargs(); # Declare a function with no arguments sub twoargs($$); # Declare a function with two scalar arguments. The two sigils act as argument type placeholders </lang>

Perl 6

There is no restriction on placement of prototype declarations. (Actually, we call them "stub declarations".) In fact, stub declarations are rarely needed in Perl 6 because post-declaration of functions is allowed, and normal function declarations do not bend the syntax the way they sometimes do in Perl 5.

Note that the ... in all of these stub bodies is literally part of the declaration syntax.

A prototype declaration for a function that does not require arguments (and returns an Int): <lang perl6>sub foo ( --> Int) {...}</lang>

A prototype declaration for a function that requires two arguments. Note that we can omit the variable name and just use the sigil in the stub, since we don't need to reference the argument until the actual definition of the routine. Also, unlike in Perl 5, a sigil like @ defaults to binding a single positional argument. <lang perl6>sub foo (@, $ --> Int) {...}</lang>

A prototype declaration for a function that utilizes varargs after one required argument. Note the "slurpy" star turns the @ sigil into a parameter that accepts all the rest of the positional arguments. <lang perl6>sub foo ($, *@ --> Int) {...}</lang>

A prototype declaration for a function that utilizes optional arguments after one required argument. Optionality is conferred by either a question mark or a default: <lang perl6>sub foo ($, $?, $ = 42 --> Int) {...}</lang>

A prototype declaration for a function that utilizes named parameters: <lang perl6>sub foo ($, :$faster, :$cheaper --> Int) {...}</lang>

Example of prototype declarations for subroutines or procedures, which in Perl 6 is done simply by noting that nothing is returned: <lang perl6>sub foo ($, $ --> Nil) {...}</lang>

A routine may also slurp up all the named arguments that were not bound earlier in the signature: <lang perl6>sub foo ($, :$option, *% --> Int) {...}</lang>

A routine may make a named parameter mandatory using exclamation mark. (This is more useful in multi subs than in stubs though.) <lang perl6>sub foo ($, :$option! --> Int) {...}</lang>