HOME

TheInfoList



OR:

In
computing Computing is any goal-oriented activity requiring, benefiting from, or creating computer, computing machinery. It includes the study and experimentation of algorithmic processes, and the development of both computer hardware, hardware and softw ...
, a procedural parameter is a
parameter A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
of a procedure that is itself a procedure. This concept is an extremely powerful and versatile programming tool, because it allows programmers to modify certain steps of a library procedure in arbitrarily complicated ways, without having to understand or modify the code of that procedure. This tool is particularly effective and convenient in languages that support local function definitions, such as Pascal and the modern GNU dialect of C. It is even more so when function closures are available. The same functionality (and more) is provided by
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
s in
object oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impleme ...
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s, but at a significantly higher cost. Procedural parameters are somewhat related to the concepts of
first-class function In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
and
anonymous function In computer programming, an anonymous function (function literal, expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for const ...
, but is distinct from them. These two concepts have more to do with how functions are defined, rather than how they are used.


Basic concept

In most languages that provide this feature, a procedural parameter ''f'' of a subroutine ''P'' can be called inside the body of ''P'' as if it were an ordinary procedure: procedure ''P''(''f''): return ''f''(6,3) * ''f''(2,1) When calling the subroutine ''P'', one must give it one argument, that must be some previously defined function compatible with the way ''P'' uses its parameter ''f''. For example, if we define procedure ''plus''(''x'', ''y''): return ''x'' + ''y'' then we may call ''P'' (''plus''), and the result will be ''plus''(6,3) * ''plus''(2,1) = (6 + 3)*(2 + 1) = 27. On the other hand, if we define procedure ''quot''(''u'', ''v''): return ''u''/''v'' then the call ''P'' (''quot'') will return ''quot''(6,3)*''quot''(2,1) = (6/3)*(2/1) = 4. Finally, if we define procedure ''evil''(''z'') return z + 100 then the call ''P'' (''evil'') will not make much sense, and may be flagged as an error.


Syntactic details

Some programming languages that have this feature may allow or require a complete type declaration for each procedural parameter ''f'', including the number and type of its arguments, and the type of its result, if any. For example, in the C programming language the example above could be written as int P(int (*f)(int a, int b)) In principle, the actual function ''actf'' that is passed as argument when ''P'' is called must be type-compatible with the declared type of the procedure parameter ''f''. This usually means that ''actf'' and ''f'' must return the same type of result, must have the same number of arguments, and corresponding arguments must have the same type. The names of the arguments need not be the same, however, as shown by the ''plus'' and ''quot'' examples above. However, some programming languages may be more restrictive or more liberal in this regard.


Scoping

In languages that allow procedural parameters, the scoping rules are usually defined in such a way that procedural parameters are executed in their native scope. More precisely, suppose that the function ''actf'' is passed as argument to ''P'', as its procedural parameter ''f''; and ''f'' is then called from inside the body of ''P''. While ''actf'' is being executed, it sees the environment of its definition. The implementation of these scoping rules is not trivial. By the time that ''actf'' is finally executed, the activation records where its environment variables live may be arbitrarily deep in the stack. This is the so-called downwards funarg problem.


Example: Generic insertion sort

The concept of procedural parameter is best explained by examples. A typical application is the following generic implementation of the
insertion sort Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Howev ...
algorithm, that takes two integer parameters ''a'',''b'' and two procedural parameters ''prec'', ''swap'': procedure ''isort''(''a'', ''b'', ''prec'', ''swap''): integer ''i'', ''j''; ''i'' ← ''a''; while ''i'' ≤ ''b'' do ''j'' ← ''i''; while ''j'' > ''a'' and ''prec''(''j'', ''j''−1) do ''swap''(''j'', ''j''−1); ''j'' ← ''j''−1; ''i'' ← ''i''+1; This procedure can be used to sort the elements ''x'' 'a''through ''x'' 'b''of some array ''x'', of arbitrary
type Type may refer to: Science and technology Computing * Typing, producing text via a keyboard, typewriter, etc. * Data type, collection of values used for computations. * File type * TYPE (DOS command), a command to display contents of a file. * ...
, in a user-specified order. The parameters ''prec'' and ''swap'' should be two
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
s, defined by the
client Client(s) or The Client may refer to: * Client (business) * Client (computing), hardware or software that accesses a remote service on another computer * Customer or client, a recipient of goods or services in return for monetary or other valuable ...
, both taking two integers ''r'', ''s'' between ''a'' and ''b''. The ''prec'' function should return true
if and only if In logic and related fields such as mathematics and philosophy, "if and only if" (often shortened as "iff") is paraphrased by the biconditional, a logical connective between statements. The biconditional is true in two cases, where either bo ...
the data stored in ''x'' 'r''should precede the data stored in ''x'' 's'' in the ordering defined by the client. The ''swap'' function should exchange the contents of ''x'' 'r''and ''x'' 's'' and return no result. By the proper choice of the functions ''prec'' and ''swap'', the same ''isort'' procedure can be used to reorder arrays of any data type, stored in any medium and organized in any
data structure In computer science, a data structure is a data organization and storage format that is usually chosen for Efficiency, efficient Data access, access to data. More precisely, a data structure is a collection of data values, the relationships amo ...
that provides indexed access to individual array elements. (Note however that there are
sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending ...
s that are much more efficient than insertion sort for large arrays.)


Sorting floating-point numbers

For instance, we can sort an array ''z'' of 20 floating-point numbers, ''z'' through ''z'' 0in increasing order by calling ''isort'' (1, 20,''zprec'',''zswap''), where the functions ''zprec'' and ''zswap'' are defined as procedure ''zprec''(''r'', ''s''): return (''z'' 'r''< ''z'' 's''; procedure ''zswap''(''r'', ''s''): float ''t''; ''t'' ← ''z'' 'r'' ''z'' 'r''← ''z'' 's'' ''z'' 's''← ''t''


Sorting rows of a matrix

For another example, let ''M'' be a
matrix Matrix (: matrices or matrixes) or MATRIX may refer to: Science and mathematics * Matrix (mathematics), a rectangular array of numbers, symbols or expressions * Matrix (logic), part of a formula in prenex normal form * Matrix (biology), the m ...
of integers with 10 rows and 20 columns, with indices starting at 1. The following code will rearrange the elements in each row so that all the even values come before all odd values: integer i procedure ''eoprec''(''r'', ''s''): return (''M'' 'i'', ''r''mod 2) < (''M'' 'i'', ''s''mod 2); procedure ''eoswap''(''r'', ''s''): integer ''t''; ''t'' ← ''M'' 'i'',''r'' ''M'' 'i'',''r''← ''M'' 'i'',''s'' ''M'' 'i'',''s''← ''t''; for ''i'' from 1 to 10 do ''isort''(1, 20, eoprec, eoswap); Note that the effects of ''eoprec'' and ''eoswap'' depend on the row number ''i'', but the ''isort'' procedure does not need to know that.


Vector-sorting procedure

The following example uses ''isort'' to define a procedure ''vecsort'' that takes an integer ''n'' and an integer vector ''v'' with elements ''v'' through ''v'' 'n''−1and sorts them in either increasing or decreasing order, depending on whether a third parameter ''incr'' is true or false, respectively: procedure ''vecsort''(''n'', ''v'', ''incr''): procedure ''vprec''(''r'', ''s''): if ''incr'' then return ''v'' 'r''< ''v'' 's'' else return ''v'' 'r''> ''v'' 's'' procedure ''vswap''(''r'', ''s''): integer ''t''; ''t'' ← ''v'' 'r'' ''v'' 'r''← ''v'' 's'' ''v'' 's''← ''t'' ''isort''(0, ''n''−1, ''vprec'', ''vswap''); Note the use of nested function definitions to get a function ''vprec'' whose effect depends on the parameter ''incr'' passed to ''vecsort''. In languages that do not allow nested function definitions, like standard C, obtaining this effect would require rather complicated and/or thread-unsafe code.


Example: merging two sequences

The following example illustrates the use of procedural parameters to process abstract data structures independently of their concrete implementation. The problem is to merge two ordered sequences of records into a single sorted sequence, where the nature of the records and the ordering criterion can be chosen by the client. The following implementation assumes only that each record can be referenced by a
memory address In computing, a memory address is a reference to a specific memory location in memory used by both software and hardware. These addresses are fixed-length sequences of digits, typically displayed and handled as unsigned integers. This numeric ...
, and there is a "null address" Λ that is not the address of any valid record. The client must provide the addresses ''A'', ''B'' of the first records in each sequence, and functions ''prec'', ''next'', and ''append'', to be described later. procedure ''merge''(''A'', ''B'', ''prec'', ''nextA'', ''appendA'', ''nextB'', ''appendB''): address ''ini'', ''fin'', ''t'' ''ini'' ← Λ; ''fin'' ← Λ while ''A'' ≠ Λ or ''B'' ≠ Λ do if ''B'' = Λ or (''A'' ≠ Λ and ''B'' ≠ Λ and ''prec''(''A'', ''B'')) then ''t'' ← ''nextA''(''A'') ''fin'' ← appendA(''A'', ''fin''); if ''ini'' = Λ then ''ini'' ← ''fin'' ''A'' ← ''t'' else ''t'' ← ''nextB''(''B'') ''fin'' ← ''appendB''(''B'', ''fin''); if ''ini'' = Λ then ''ini'' ← ''fin'' ''B'' ← ''t'' return ''ini'' The function ''prec'' should take the addresses ''r'', ''s'' of two records, one from each sequence, and return true if the first record should come before the other in the output sequence. The function ''nextA'' should take the address of a record from the first sequence, and return the address of the next record in the same sequence, or Λ if there is none. The function ''appendA'' should append the first record from sequence ''A'' to the output sequence; its arguments are the address ''A'' of the record to be appended, and the address ''fin'' of the last record of the output list (or Λ if that list is still empty). The procedure ''appendA'' should return the updated address of the final element of the output list. The procedures ''nextB'' and ''appendB'' are analogous for the other input sequence.


Merging linked lists

To illustrate the use of the generic merge procedure, here is the code for merging two simple
linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whi ...
s, starting with nodes at addresses ''R'', ''S''. Here we assume that each record ''x'' contains an integer field ''x''.''INFO'' and an address field ''x''.''NEXT'' that points to the next node; where the ''info'' fields are in increasing order in each list. The input lists are dismantled by the merge, and their nodes are used to build the output list. procedure ''listmerge''(''R'', ''S''): procedure ''prec''(''r'', ''s''): return ''r''.''INFO'' < ''s''.''INFO'' procedure ''next''(''x''): return ''x''.''NEXT'' procedure ''append''(''x'', ''fin'') if ''fin'' ≠ Λ then ''fin''.''NEXT'' ← ''x'' ''x''.''NEXT'' ← Λ return ''x'' return ''merge''(''R'', ''S'', ''prec'', ''next'', ''append'', ''next'', ''append'')


Merging vectors

The following code illustrates the independence of the generic ''merge'' procedure from the actual representation of the sequences. It merges the elements of two ordinary arrays ''U'' through ''U'' 'm''−1and ''V'' through ''V'' 'n''−1of floating-point numbers, in decreasing order. The input arrays are not modified, and the merged sequence of values is stored into a third vector ''W'' through ''W'' 'm''+''n''−1 As in the C programming language, we assume that the expression "&''V''" yields the address of variable ''V'', "*''p''" yields the variable whose address is the value of ''p'', and that "&(''X'' 'i''" is equivalent to "&(''X'' + ''i''" for any array ''X'' and any integer ''i''. procedure ''arraymerge''(''U'', ''m'', ''V'', ''n'', ''W''): procedure ''prec''(''r'', ''s''): return (*''r'') > (*''s'') procedure ''nextU''(''x''): if ''x'' = &(''U'' 'm''−1 then return Λ else return ''x'' + 1 procedure ''nextV''(''x''): if ''x'' = &(''V'' 'n''−1 then return Λ else return ''x'' + 1 procedure ''append''(''x'', ''fin'') if ''fin'' = Λ then ''fin'' ← &(''W'' (*''fin'') ← (*''x'') return ''fin'' + 1 if ''m'' = 0 then ''U'' ← Λ if ''n'' = 0 then ''V'' ← Λ return ''merge''(''U'', ''V'', ''prec'', ''nextU'', ''append'', ''nextV'', ''append'')


Example: Definite integral


Integrating over an interval

The following procedure computes the approximate
integral In mathematics, an integral is the continuous analog of a Summation, sum, which is used to calculate area, areas, volume, volumes, and their generalizations. Integration, the process of computing an integral, is one of the two fundamental oper ...
\textstyle\int_a^b ''f'' (''x'') d''x'' of a given real-valued
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-orie ...
''f'' over a given interval 'a'',''b''of the
real line A number line is a graphical representation of a straight line that serves as spatial representation of numbers, usually graduated like a ruler with a particular origin (geometry), origin point representing the number zero and evenly spaced mark ...
. The
numerical method In numerical analysis, a numerical method is a mathematical tool designed to solve numerical problems. The implementation of a numerical method with an appropriate convergence check in a programming language is called a numerical algorithm. Mathem ...
used is the trapezium rule with a given number ''n'' of steps; the real numbers are approximated by floating-point numbers. procedure ''Intg''(''f'', ''a'', ''b'', ''n''): float ''t'', ''x'', ''s''; integer ''i'' if ''b'' = ''a'' then return 0 ''x'' ← ''a''; ''s'' ← ''f''(''a'') / 2; for i from 1 to ''n''−1 do ''t'' ← ''i''/(''n''+1); ''x'' ← (1−''t'') * ''a'' + ''t'' * ''b''; ''s'' ← ''s'' + ''f''(''x'') ''s'' ← ''f''(''b'') / 2 return (''b'' − ''a'') * ''s'' / ''n''


Integrating over a disk

Consider now the problem of integrating a given function g, with two arguments, over a disk D with given center (xc,yc) and given radius R. This problem can be reduced to two nested single-variable integrals by the change of variables :\int\!\int_D g(x,y)\, \mathrmx\, \mathrmy = \int_0^R z \left(\int_0^ g(\mathit+z \cos t ,\mathit+z \sin t ) \,\mathrmt\right)\,\mathrmz The following code implements the right-hand-side formula: procedure ''DiskIntg''(''g'', ''xc'', ''yc'', ''R'', ''n'') procedure ''gring''(''z''): procedure ''gpolar''(''t''): float ''x'', ''y'' ''x'' ← ''xc'' + ''z'' * ''cos''(''t'') ''y'' ← ''yc'' + ''z'' * ''sin''(''t'') return ''g''(''x'', ''y'') integer ''m'' ← ''round''(''n''*''z''/''R'') return ''z'' * ''Intg''(''gpolar'', 0, 2*π, ''m'') return ''Intg''(''gring'', 0, ''R'', ''n'') This code uses the integration procedure ''Intg'' in two levels. The outer level (last line) uses ''Intg'' to compute the integral of gring(z) for z varying from 0 to R. The inner level (next-to-last line) defines gring(z) as being the
line integral In mathematics, a line integral is an integral where the function (mathematics), function to be integrated is evaluated along a curve. The terms ''path integral'', ''curve integral'', and ''curvilinear integral'' are also used; ''contour integr ...
of g(x,y) over the circle with center (xc,yc) and radius z.


History

Procedural parameters were invented before the age of electronic computers, by
mathematician A mathematician is someone who uses an extensive knowledge of mathematics in their work, typically to solve mathematical problems. Mathematicians are concerned with numbers, data, quantity, mathematical structure, structure, space, Mathematica ...
Alonzo Church Alonzo Church (June 14, 1903 – August 11, 1995) was an American computer scientist, mathematician, logician, and philosopher who made major contributions to mathematical logic and the foundations of theoretical computer science. He is bes ...
, as part of his
lambda calculus In mathematical logic, the lambda calculus (also written as ''λ''-calculus) is a formal system for expressing computability, computation based on function Abstraction (computer science), abstraction and function application, application using var ...
model of computation. Procedural parameters as a programming language feature were introduced by
ALGOL 60 ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a ...
. In fact, ALGOL 60 had a powerful "
call by name In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the ...
" parameter-passing mechanism that could simplify some uses of procedural parameters; see Jensen's Device. Procedural parameters were an essential feature of the
LISP programming language Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
, which also introduced the concept of function closure or funarg. The
C programming language C (''pronounced'' '' – like the letter c'') is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of ...
allows
function pointers A function pointer, also called a subroutine pointer or procedure pointer, is a pointer (computer programming), pointer referencing executable code, rather than data. dereference operator, Dereferencing the function pointer yields the referenced s ...
to be passed as parameters, which accomplish the same end, and are often used as
callbacks In computer programming, a callback is a function that is stored as data (a reference) and designed to be called by another function often ''back'' to the original abstraction layer. A function that accepts a callback parameter may be design ...
in
event-driven programming In computer programming, event-driven programming is a programming paradigm in which the Control flow, flow of the program is determined by external Event (computing), events. User interface, UI events from computer mouse, mice, computer keyboard, ...
and as error handlers. However, only a few modern C compilers allow nested function definitions, so that its other uses are relatively uncommon. Procedural parameters were provided also in Pascal, together with nested procedure definitions; however, since standard Pascal did not allow separate compilation, the feature was little used in that language, too.


See also

*
Function pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments ...
*
Functional programming In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declarat ...
*
Funarg problem In computer science, the funarg problem ''(function argument problem)'' refers to the difficulty in implementing first-class functions (functions as first-class objects) in programming language implementations so as to use stack-based memory allocat ...
*
Design patterns (computer science) In software engineering, a software design pattern or design pattern is a general, reusability, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted dir ...


References

{{DEFAULTSORT:Procedural Parameter Subroutines