Function prototype: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added zkl)
Line 439: Line 439:


<lang perl>sub noargs(); # Declare a function with no arguments
<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>
sub twoargs($$); # Declare a function with two scalar arguments. The two sigils act as argument type placeholders
sub noargs :prototype(); # Using the :attribute syntax instead
sub twoargs :prototype($$);</lang>


=={{header|Perl 6}}==
=={{header|Perl 6}}==

Revision as of 16:48, 1 July 2014

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

In Ada, prototypes are called specifications.

  • Specifications must be an exact copy of everything prior to the "is" statement for a function or procedure.
  • All specifications must appear in a declarative section, ie: before a "begin" statement.
  • For a main program, specifications are only necessary if a function call appears in the source before the function definition.
  • For a package, specifications must appear as part of the specification(.ads) file, and do not appear in the body file(.adb) (The file extensions apply to Gnat Ada and may not apply to all compilers).

<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> Example of a package specification (i.e. prototype): <lang Ada>package Stack is

  procedure Push(Object:Integer);
  function Pull return Integer;

end Stack;</lang>

Example of a package body: <lang Ada>package body Stack is

  procedure Push(Object:Integer) is
  begin
     -- implementation goes here
  end;
  function Pull return Integer;
  begin
     -- implementation goes here
  end;

end Stack;</lang>

To use the package and function: <lang Ada>with Stack; procedure Main is

  N:integer:=5;

begin

  Push(N);
  ...
  N := Pull;

end Main;</lang>

Aime

<lang aime>integer f0(void); # No arguments void f1(integer, real); # Two arguments real f2(...); # Varargs void f3(integer, ...); # Varargs

void f4(integer &, text &); # Two arguments (integer and string), pass by reference integer f5(integer, integer (*)(integer));

                               # Two arguments: integer and function returning integer and taking one integer argument

integer f6(integer a, real b); # Parameters names are allowed record f7(void); # Function returning an associative array</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(void); /* Declare a function with no argument that returns an integer */ int twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */ int twoargs(int ,int); /* Parameter names are optional in a prototype definition */ int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */ int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */</lang>

C++

Function declaration in C++ differs from that in C in some aspect.

<lang cpp>int noargs(); // Declare a function with no arguments that returns an integer int twoargs(int a,int b); // Declare a function with two arguments that returns an integer int twoargs(int ,int); // Parameter names are optional in a prototype definition int anyargs(...); // An ellipsis is used to declare a function that accepts varargs int atleastoneargs(int, ...); // One mandatory integer argument followed by varargs template<typename T> T declval(T); //A function template template<typename ...T> tuple<T...> make_tuple(T...); //Function template using parameter pack (since c++11) </lang>

COBOL

Prototypes were introduced in COBOL 2002. In the following examples, PROGRAM-ID and PROGRAM can be replaced with the equivalents for functions and methods. However, in method prototypes the PROTOTYPE clause is not used.

<lang cobol> *> A subprogram taking no arguments and returning nothing.

      PROGRAM-ID. no-args PROTOTYPE.
      END PROGRAM no-args.
      *> A subprogram taking two 8-digit numbers as arguments, and returning
      *> an 8-digit number.
      PROGRAM-ID. two-args PROTOTYPE.
      DATA DIVISION.
      LINKAGE SECTION.
      01  arg-1 PIC 9(8).
      01  arg-2 PIC 9(8).
      01  ret   PIC 9(8).
      PROCEDURE DIVISION USING arg-1, arg-2 RETURNING ret.
      END PROGRAM two-args.
      *> A subprogram taking two optional arguments which are 8-digit
      *> numbers (passed by reference (the default and compulsory for
      *> optional arguments)).
      PROGRAM-ID. optional-args PROTOTYPE.
      DATA DIVISION.
      LINKAGE SECTION.
      01  arg-1 PIC 9(8).
      01  arg-2 PIC 9(8).
      PROCEDURE DIVISION USING OPTIONAL arg-1, OPTIONAL arg-2.
      END PROGRAM optional-args.
      *> Standard COBOL does not support varargs or named parameters.
      *> A function from another language, taking a 32-bit integer by
      *> value and returning a 32-bit integer (in Visual COBOL).
      PROGRAM-ID. foreign-func PROTOTYPE.
      OPTIONS.
          ENTRY-CONVENTION some-langauge.
      DATA DIVISION.
      WORKING-STORAGE SECTION.
      01  arg PIC S9(9) USAGE COMP-5.
      01  ret PIC S9(9) USAGE COMP-5.
      PROCEDURE DIVISION USING arg RETURNING ret.
      END PROGRAM foreign-func.</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>

F#

In F#, prototypes are called signatures. Signature files are used to bulk annotate the accessibility of the things within them. If something is in an implementation file but not in the signature file, it is assumed to be private to that file. If it is in the signature file without the internal accessibility modifier, then it is assumed to public, otherwise it is internal to the assembly. For more details, see the documentation. Below is an example of the signatures produced for the functions specified in the task (without any accessibility modifiers): <lang fsharp>// A function taking and returning nothing (unit). val noArgs : unit -> unit // A function taking two integers, and returning an integer. val twoArgs : int -> int -> int // A function taking a ParamPack array of ints, and returning an int. The ParamPack // attribute is not included in the signature. val varArgs : int [] -> int // A function taking an int and a ParamPack array of ints, and returning an // object of the same type. val atLeastOnArg : int -> int [] -> int // A function taking an int Option, and returning an int. val optionalArg : Option<int> -> int

// Named arguments and the other form of optional arguments are only available on // methods. type methodClass =

 class
   // A method taking an int named x, and returning an int.
   member NamedArg : x:int -> int
   // A method taking two optional ints in a tuple, and returning an int. The
   //optional arguments must be tupled.
   member OptionalArgs : ?x:int * ?y:int -> int
 end</lang>

Go

While the language specification does not use the word prototype it states, "A function declaration may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine." This is the closest analogy to a C (e.g.) prototype.

Function declarations whether with a body or without must be "top level" declarations, that is, after the package clause and outside of any other function. Examples of function delarations without bodies are, <lang go>func a() // function with no arguments func b(x, y int) // function with two arguments func c(...int) // varargs are called "variadic parameters" in Go.</lang> Go does not directly support optional or named parameters and does not have any concept of procedures or subroutines as distinct from functions.

Otherwise, Go does have the concept of a function signature which includes parameters and return values. Go is strongly typed and functions are first class objects so function signatures are used in a variety of ways. These might be considered distinct from the concept of function prototype.

J

J assumes an unknown name is a verb of infinite rank. Rank determines the frames on which the verb executes. As the demonstration shows, changing the rank, assigning the rank before the verb is used in other definitions affects the result. We could, of course, play other games by changing the unknown name from verb to another part of speech. <lang J> NB. j assumes an unknown name f is a verb of infinite rank

  NB. f has infinite ranks
  f b. 0

_ _ _

  NB. The verb g makes a table.
  g=: f/~
  NB. * has rank 0
  f=: *


  NB. indeed, make a multiplication table
  f/~ i.5

0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16

  NB. g was defined as if f had infinite rank.
  g i.5

0 1 4 9 16

  NB. f is known to have rank 0.
  g=: f/~
  NB. Now we reproduce the table
  g i.5

0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16


  NB. change f to another rank 0 verb
  f=: +   
  NB. and construct an addition table
  g i.5

0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8


  NB. f is multiplication at infinite rank
  f=: *"_
  
  NB. g, however, has rank 0
  g i.5

0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16</lang>

JavaScript

ES5

JavaScript functions may also be used to define prototype objects <lang JavaScript> // A prototype declaration for a function that does not require arguments function List() {}

List.prototype.push = function() {

 return [].push.apply(this, arguments);

};

List.prototype.pop = function() {

 return [].pop.call(this);

};

var l = new List(); l.push(5); l.length; // 1 l[0]; 5 l.pop(); // 5 l.length; // 0

// A prototype declaration for a function that utilizes varargs function List() {

 this.push.apply(this, arguments);

}

List.prototype.push = function() {

 return [].push.apply(this, arguments);

};

List.prototype.pop = function() {

 return [].pop.call(this);

};

var l = new List(5, 10, 15); l.length; // 3 l[0]; 5 l.pop(); // 15 l.length; // 2

</lang>

ES6

Class Declarations are used to define prototype objects <lang JavaScript> // A prototype declaration for a function that does not require arguments class List {

 push() {
   return [].push.apply(this, arguments);
 }
 pop() {
   return [].pop.call(this);  
 }

}

var l = new List(); l.push(5); l.length; // 1 l[0]; 5 l.pop(); // 5 l.length; // 0


// A prototype declaration for a function that utilizes varargs class List {

 constructor(...args) {
   this.push(...args);
 }
 push() {
   return [].push.apply(this, arguments);
 }
 pop() {
   return [].pop.call(this);  
 }

}

var l = new List(5, 10, 15); l.length; // 3 l[0]; 5 l.pop(); // 15 l.length; // 2 </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 sub noargs :prototype(); # Using the :attribute syntax instead sub twoargs :prototype($$);</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>

PL/I

<lang pli> declare s1 entry; declare s2 entry (fixed); declare s3 entry (fixed, float);

declare f1 entry returns (fixed); declare f2 entry (float) returns (float); declare f3 entry (character(*), character(*)) returns (character (20)); </lang>

Racket

Most of the points are covered in this program <lang racket>

  1. lang racket

(define (no-arg) (void))

(define (two-args a b) (void)) ;arguments are always named

(define (varargs . args) (void)) ;the extra arguments are stored in a list

(define (varargs2 a . args) (void)) ;one obligatory argument and the rest are contained in the list

(define (optional-arg (a 5)) (void)) ;a defaults to 5</lang>

(void) is a function that returns "nothing", so this are prototypes that do nothing. Although standard Racket doesn't allow type declarations, it allows contracts, so we can add this to the previous declarations <lang racket> (provide (contract-out

         [two-args (integer? integer? . -> . any)]))</lang>

then any module that imports the function can only pass integers to two-args.

Another way is using the typed/racket language, like this <lang racket>

  1. lang typed/racket

(: two-args (Integer Integer -> Any)) (define (two-args a b) (void))</lang>

zkl

In zkl, all functions are var args. Prototypes provide provide some documentation and an overlay on the incoming args. Named parameters are not supported. <lang zkl>fcn{"Hello World"} // no expected args fcn(){"Hello World"} // ditto

fcn{vm.arglist}(1,2) // ask the VM for the passed in args -->L(1,2) fcn f(a,b){a+b} // fcn(1,2,3) works just fine fcn f(args){}(1,2,3) //args = 1 fcn(args){vm.arglist.sum()}(1,2,3) //-->6

fcn(a=1,b=2){vm.arglist}() //-->L(1,2) fcn(a=1,b=2){vm.arglist}(5) //-->L(5,2) fcn(a=1,b){vm.arglist}() //-->L(1), error if you try to use b fcn(a,b=2){vm.arglist}(5) //-->L(5,2) fcn(a,b=2,c){vm.arglist}(1) //-->L(1,2)

fcn(){vm.nthArg(1)}(5,6) //-->6 fcn{vm.numArgs}(1,2,3,4,5,6,7,8,9) //-->9 fcn{vm.argsMatch(...)} // a somewhat feeble attempt arg pattern matching based on type (vs value)

  // you can do list assignment in the prototype:

fcn(a,[(b,c)],d){vm.arglist}(1,L(2,3,4),5) //-->L(1,L(2,3,4),5) fcn(a,[(b,c)],d){"%s,%s,%s,%s".fmt(a,b,c,d)}(1,L(2,3,4),5) //-->1,2,3,5

  // no type enforcement but you can give a hint to the compiler

fcn([Int]n){n.sin()} //--> syntax error as Ints don't do sin</lang>