Function definition: Difference between revisions
No edit summary |
Added uBasic/4tH version |
||
Line 1,899: | Line 1,899: | ||
Return values are usually put into the register EAX. This, of course is not a must it's simply that it's somewhat of a unofficial standard. For example, C/C++ preprocessors/compilers will translate "return value" into "mov eax, value" followed by the return to caller instruction "ret". |
Return values are usually put into the register EAX. This, of course is not a must it's simply that it's somewhat of a unofficial standard. For example, C/C++ preprocessors/compilers will translate "return value" into "mov eax, value" followed by the return to caller instruction "ret". |
||
=={{header|uBasic/4tH}}== |
|||
In uBasic you can turn any subroutine into a function with the '''FUNC()''' function. It takes one argument, which is the label. Arguments are optional. |
|||
<lang>PRINT FUNC (_Multiply (2,3)) |
|||
END |
|||
_Multiply PARAM (2) |
|||
RETURN (a@ * b@)</lang> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
<lang XPL0>func Multiply(A, B); \the characters in parentheses are only a comment |
<lang XPL0>func Multiply(A, B); \the characters in parentheses are only a comment |
||
Line 1,908: | Line 1,915: | ||
real A, B; \arguments are declared here as floating point (doubles) |
real A, B; \arguments are declared here as floating point (doubles) |
||
return A*B;</lang> |
return A*B;</lang> |
||
=={{header|XSLT}}== |
=={{header|XSLT}}== |
||
Templates are the closest things XSLT has to user defined functions. They can be declared to be called by name and/or to be applied to all nodes in a matching set and given "mode". Both types of template can take named parameters with default values. Templates also have a "context" node used as the base of XPath expressions (kind of like an implied "this" of an object's method). |
Templates are the closest things XSLT has to user defined functions. They can be declared to be called by name and/or to be applied to all nodes in a matching set and given "mode". Both types of template can take named parameters with default values. Templates also have a "context" node used as the base of XPath expressions (kind of like an implied "this" of an object's method). |
Revision as of 13:02, 7 July 2015
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function.
Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned).
See also:Function prototype
8051 Assembly
Like other assembly languages, 8051 doesn't have functions but instead has symbolic references to code. Function arguments are passed via registers decided on beforehand. <lang asm>ORG RESET mov a, #100 mov b, #10 call multiply
- at this point, the result of 100*10 = 1000 = 03e8h is stored in registers a and b
- a = e8
- b = 03
jmp $
multiply: mul ab ret</lang>
ACL2
<lang Lisp>(defun multiply (a b) (* a b))</lang>
ActionScript
<lang actionscript>function multiply(a:Number, b:Number):Number {
return a * b;
}</lang>
Ada
<lang ada>function Multiply (A, B : Float) return Float;</lang> and an implementation of: <lang ada>function Multiply (A, B : Float) return Float is begin
return A * B;
end Multiply;</lang>
The Ada 2012 standard provides an even simpler way to define and implement functions:
<lang Ada>function Multiply(A, B: Float) return Float is (A * B);</lang>
Ada supports generic functions which can take generic formal parameters like the numeric type to use:
<lang ada>generic
type Number is digits <>;
function Multiply (A, B : Number) return Number;</lang> implemented as: <lang ada>function Multiply (A, B : Number) return Number is begin
return A * B;
end Multiply;</lang> To use this, you need to instantiate the function for each type e.g. <lang ada> with Multiply; ... function Multiply_Integer is new Multiply(Number => Integer); use Multiply_Integer; -- If you must
type My_Integer is Range -100..100; function Multiply_My_Integer is new Multiply(My_Integer); </lang>
Aime
<lang aime>real multiply(real a, real b) {
return a * b;
}</lang>
ALGOL 68
<lang algol68>PROC multiply = ( LONG REAL a, b ) LONG REAL: (
a * b
)</lang>
ALGOL W
<lang algolw>long real procedure multiply( long real value a, b ); begin
a * b
end</lang>
AmigaE
<lang amigae>PROC my_molt(a,b) -> other statements if needed... here they are not ENDPROC a*b -> return value
-> or simplier
PROC molt(a,b) IS a*b
PROC main()
WriteF('\d\n', my_molt(10,20))
ENDPROC</lang>
APL
<lang apl> multiply ← ×</lang> Works on arrays of any rank (any number of dimensions): atoms, lists, tables, etc.
AppleScript
<lang AppleScript>on multiply(a, b)
return a * b
end</lang>
Applesoft BASIC
Applesoft BASIC functions are unary meaning they only take one argument. As the task asks for a multiply function which takes two arguments this poses a problem. To get around this, the multiply function MU takes one argument as the offset into an array of parameters.
Function names in Applesoft BASIC can be longer than two characters but only the first two characters are significant. Function names cannot contain any keywords.
<lang basic>10 DEF FN MULTIPLY(P) = P(P) * P(P+1) 20 P(1) = 611 : P(2) = 78 : PRINT FN MULTIPLY(1)</lang>
<lang basic>47658</lang>
Argile
<lang Argile>use std .: multiply <real a, real b> :. -> real {a * b}</lang> with a macro and a variable number of parameters: <lang Argile>use std =: multiply <real a> [<real b>...] := -> real {Cgen a (@@1 (Cgen " * " b))}</lang>
AutoHotkey
<lang autohotkey>MsgBox % multiply(10,2)
multiply(multiplicand, multiplier) {
Return (multiplicand * multiplier)
}</lang>
AutoIt
<lang AutoIt>#AutoIt Version: 3.2.10.0 $I=11 $J=12 MsgBox(0,"Multiply", $I &" * "& $J &" = " & product($I,$J)) Func product($a,$b)
Return $a * $b
EndFunc</lang>
AWK
<lang awk>function multiply(a, b) {
return a*b
} BEGIN {
print multiply(5, 6)
}</lang>
Axe
<lang axe>Lbl MULT r₁*r₂ Return</lang>
BASIC
<lang qbasic>DECLARE FUNCTION multiply% (a AS INTEGER, b AS INTEGER)
FUNCTION multiply% (a AS INTEGER, b AS INTEGER)
multiply = a * b
END FUNCTION</lang>
Batch File
Windows batch files only have procedures, not functions. Instead, environmental variables can be used as a global shared state. <lang>@ECHO OFF SET /A result = 0 CALL :multiply 2 3 ECHO %result% GOTO :eof
- multiply
SET /A result = %1 * %2 GOTO :eof
- eof</lang>
BBC BASIC
BBC BASIC supports both single-line and multi-line function definitions. Note that the function name must begin with FN.
Single-line function: <lang bbcbasic>PRINT FNmultiply(6,7) END
DEF FNmultiply(a,b) = a * b</lang> Multiline function: <lang bbcbasic>DEF FNmultiply(a,b) LOCAL c c = a * b = c</lang>
bc
<lang bc>define multiply(a, b) { return a*b }
print multiply(2, 3)</lang>
Boo
<lang boo>def multiply(x as int, y as int):
return x * y
print multiply(3, 2)</lang>
Bracmat
<lang bracmat>multiply=a b.!arg:(?a.?b)&!a*!b; out$multiply$(123456789.987654321); { writes 121932631112635269 to standard output }</lang>
Brat
<lang brat>multiply = { x, y | x * y }
p multiply 3 14 #Prints 42</lang>
C
<lang c>double multiply(double a, double b) {
return a * b;
}</lang>
Macros
Macros can be defined at the top of a program and the compiler will replace the function calls with the function itself before compiling the program (the source file will not change). <lang c>#define MULTIPLY(X, Y) ((X) * (Y))</lang> Parentheses should be added around parameters in the function definition to avoid order of operations errors when someone uses the macro as such: <lang c>x = MULTIPLY(x + z, y);</lang> A program with that call would be compiled as if this were coded instead: <lang c>x = ((x + z) * (y));</lang> Another advantage of macros is that they work with all types alike. For example, the above macro can be used both to multiply double values (like the function above), and to multiply int values (giving an int, which the function doesn't).
C#
<lang csharp>static double multiply(double a, double b) {
return a * b;
}</lang> Anonymous function: <lang csharp>Func<double, double, double> multiply = ((a,b) => a*b);</lang>
ChucK
<lang> fun float multiply (float a, float b) {
return a * b;
} // uncomment next line and change values to test //<<< multiply(16,4) >>>; </lang>
C++
C++ functions basically are the same as in C. Also macros exist, however they are discouraged in C++ in favour of inline functions and function templates.
An inline function differs from the normal function by the keyword inline and the fact that it has to be included in every translation unit which uses it (i.e. it normally is written directly in the header). It allows the compiler to eliminate the function without having the disadvantages of macros (like unintended double evaluation and not respecting scope), because the substitution doesn't happen at source level, but during compilation. An inline version of the above function is: <lang cpp>inline double multiply(double a, double b) {
return a*b;
}</lang> If not only doubles, but numbers of arbitrary types are to be multiplied, a function template can be used: <lang cpp>template<typename Number>
Number multiply(Number a, Number b)
{
return a*b;
}</lang> Of course, both inline and template may be combined (the inline then has to follow the template<...>), but since templates have to be in the header anyway (while the standard allows them to be compiled separately using the keyword export, almost no compiler implements that), the compiler usually can inline the template even without the keyword.
Clay
<lang Clay>multiply(x,y) = x * y;</lang>
Clojure
<lang lisp>(defn multiply [x y]
(* x y))
(multiply 4 5)</lang> Or with multiple arities (in the manner of the actual * function): <lang lisp>(defn multiply
([] 1) ([x] x) ([x y] (* x y)) ([x y & more] (reduce * (* x y) more)))
(multiply 2 3 4 5) ; 120</lang>
COBOL
In COBOL, multiply is a reserved word, so the requirements must be relaxed to allow a different function name. The following uses a program:
<lang COBOL> IDENTIFICATION DIVISION.
PROGRAM-ID. myTest. DATA DIVISION. WORKING-STORAGE SECTION. 01 x PIC 9(3) VALUE 3. 01 y PIC 9(3) VALUE 2. 01 z PIC 9(9). PROCEDURE DIVISION. CALL "myMultiply" USING BY CONTENT x, BY CONTENT y, BY REFERENCE z. DISPLAY z. STOP RUN. END PROGRAM myTest.
IDENTIFICATION DIVISION. PROGRAM-ID. myMultiply. DATA DIVISION. LINKAGE SECTION. 01 x PIC 9(3). 01 y PIC 9(3). 01 z PIC 9(9). PROCEDURE DIVISION USING x, y, z. MULTIPLY x BY y GIVING z. EXIT PROGRAM. END PROGRAM myMultiply.</lang>
This example uses user-defined functions, which were added in COBOL 2002.
<lang cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. myTest. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION myMultiply. DATA DIVISION. WORKING-STORAGE SECTION. 01 x PIC 9(3) VALUE 3. 01 y PIC 9(3) VALUE 2. PROCEDURE DIVISION. DISPLAY myMultiply(x, y). STOP RUN. END PROGRAM myTest.
IDENTIFICATION DIVISION. FUNCTION-ID. myMultiply. DATA DIVISION. LINKAGE SECTION. 01 x PIC 9(3). 01 y PIC 9(3). 01 z pic 9(9). PROCEDURE DIVISION USING x, y RETURNING z. MULTIPLY x BY y GIVING z. EXIT FUNCTION. END FUNCTION myMultiply.</lang>
Coco
As CoffeeScript. In addition, Coco provides some syntactic sugar for accessing the arguments
array reminiscent of Perl's @_
:
<lang coco>multiply = -> @@0 * @@1</lang>
Furthermore, when no parameter list is defined, the first argument is available as it
:
<lang coco>double = -> 2 * it</lang>
CoffeeScript
<lang coffeescript>multiply = (a, b) -> a * b</lang>
ColdFusion
<lang coldfusion><cffunction name="multiply" returntype="numeric"> <cfargument name="a" type="numeric"> <cfargument name="b" type="numeric"> <cfreturn a * b> </cffunction></lang>
Common Lisp
Common Lisp has ordinary functions and generic functions.
Ordinary Functions
Ordinary functions operate on the values of argument expressions. Lisp functions terminate by returning one or more values, or by executing a non-local dynamic control transfer, in which case values are not returned. <lang lisp>(defun multiply (a b)
(* a b))
(multiply 2 3)</lang>
User-Defined Compiler Optimization of Functions
In Lisp we can express optimizations of calls to a function using compiler macros. For instance, suppose we know that the multiply function, which may be in another module, simply multiplies numbers together. We can replace a call to multiply by a constant, if the arguments are constant expressions. Like the usual kind of Lisp macro, the compiler macro takes the argument forms as arguments, not the argument values. The special keyword &whole gives the macro access to the entire expression, which is convenient for the unhandled cases, whereby no transformation takes place: <lang lisp>(define-compiler-macro multiply (&whole expr a b)
(if (and (constantp a) (constantp b)) (* (eval a) (eval b)) expr)) ;; no macro recursion if we just return expr; the job is done! </lang>
Lisp implementations do not have to honor compiler macros. Usually compilers make use of them, but evaluators do not.
Here is test of the macro using a CLISP interactive session. Note that the multiply function is not actually defined, yet it compiles and executes anyway, which shows that the macro provided the translation something.
$ clisp -q [1]> (define-compiler-macro multiply (&whole expr a b) (if (and (constantp a) (constantp b)) (* (eval a) (eval b)) expr)) MULTIPLY [2]> (defun test1 () (multiply 2 3)) TEST1 [3]> (compile 'test1) TEST1 ; NIL ; NIL [4]> (disassemble 'test1) Disassembly of function TEST1 (CONST 0) = 6 [ ... ] 2 byte-code instructions: 0 (CONST 0) ; 6 1 (SKIP&RET 1) NIL [5]> (test1) 6
Generic Functions
Lisp's generic functions are part of the object system. Generic functions are compiled to ordinary functions, and so are called in the ordinary way. Internally, however, they have the special behavior of dispatching one or more methods based on specializable parameters.
Methods can be defined right inside the DEFGENERIC construct, but usually are written with separate DEFMETHODS.
Also, the DEFGENERIC is optional, since the first DEFMETHOD will define the generic function, but good practice. <lang lisp>
- terrific example coming
</lang>
Creative Basic
<lang Creative Basic> DECLARE Multiply(N1:INT,N2:INT)
DEF A,B:INT
A=2:B=2
OPENCONSOLE
PRINT Multiply(A,B)
PRINT:PRINT"Press any key to close."
DO:UNTIL INKEY$<>""
CLOSECONSOLE
END
SUB Multiply(N1:INT,N2:INT)
DEF Product:INT
Product=N1*N2
RETURN Product
'Can also be written with no code in the subroutine and just RETURN N1*N2. </lang>
D
<lang d>// A function: int multiply1(int a, int b) {
return a * b;
}
// Functions like "multiply1" can be evaluated at compile time if // they are called where a compile-time constant result is asked for: enum result = multiply1(2, 3); // Evaluated at compile time. int[multiply1(2, 4)] array; // Evaluated at compile time.
// A templated function: T multiply2(T)(T a, T b) {
return a * b;
}
// Compile-time multiplication can also be done using templates: enum multiply3(int a, int b) = a * b;
pragma(msg, multiply3!(2, 3)); // Prints "6" during compilation.
void main() {
import std.stdio; writeln("2 * 3 = ", result);
}</lang> Both the compile-time and run-time output:
6 2 * 3 = 6
dc
For dc, the functions (called macros) are limited to names from 'a' to 'z' Create a function called 'm' <lang dc>[*] sm</lang> Use it (lm loads the function in 'm',x executes it, f shows the the stack.) <lang dc>3 4 lm x f = 12</lang>
Delphi
<lang Delphi>function Multiply(a, b: Integer): Integer; begin
Result := a * b;
end;</lang>
Déjà Vu
<lang dejavu>multiply a b:
* a b</lang>
DWScript
<lang Delphi>function Multiply(a, b : Integer) : Integer; begin
Result := a * b;
end;</lang>
E
<lang e>def multiply(a, b) {
return a * b
}</lang> (This does not necessarily return a product, but whatever the "multiply" method of a returns. The parameters could be guarded to only accept standard numbers.)
It is also possible to write short anonymous function definitions which do not need explicit returns: <lang e>def multiply := fn a, b { a * b }</lang> This definition is identical to the previous except that the function object will not know its own name.
Efene
<lang efene>multiply = fn (A, B) {
A * B
}
@public run = fn () {
io.format("~p~n", [multiply(2, 5)])
}</lang>
Eiffel
<lang Eiffel> multiply(a, b: INTEGER): INTEGER do Result := a*b end </lang>
Ela
<lang Ela>multiply x y = x * y</lang> Anonymous function: <lang Ela>\x y -> x * y</lang>
Elixir
<lang elixir>defmodule RosettaCode do
def multiply(x,y) do x * y end def task, do: IO.puts multiply(3,5)
end
RosettaCode.task</lang>
- Output:
15
Emacs Lisp
<lang Lisp>(defun multiply (x y)
(* x y))</lang>
A "docstring" can be added as follows. This is shown by the Emacs help system and is good for human users. It has no effect on execution.
<lang Lisp>(defun multiply (x y)
"Return the product of X and Y." (* x y))</lang>
Erlang
<lang erlang>% Implemented by Arjun Sunel -module(func_definition). -export([main/0]).
main() -> K=multiply(3,4), io :format("~p~n",[K]).
multiply(A,B) -> case {A,B} of {A, B} -> A * B end.</lang>
- Output:
12 ok
ERRE
A statement function in ERRE is a single line function definition as in Fortran 77 or BASIC. These are useful in defining functions that can be expressed with a single formula. A statement function should appear in declaration part of the program. The format is simple - just type
FUNCTION f(x,y,z,…) f=formula END FUNCTION
The main features of function statement are:
1) You can use relational operators, so it's possible to "compact" an IF THEN ELSE statement but not loop statements: you must use a procedure for these.
2) Functions can have their own identifier (integer, string, real,double).
3) It's possible to declare function with no parameter: use FUNCTION f()........
4) Functions always return one value.
5) ERRE for C-64 admits only real with one parameter functions.
FUNCTION MULTIPLY(A,B) MULTIPLY=A*B END FUNCTION
Usage:
IF MULTIPLY(A,B)>10 THEN ......
or
S=MULTIPLY(22,11)
Euphoria
<lang Euphoria>function multiply( atom a, atom b )
return a * b
end function</lang>
If you declare the arguments as object
then sequence comprehension kicks in:
<lang Euphoria>function multiply( object a, object b )
return a * b
end function
sequence a = {1,2,3,4} sequence b = {5,6,7,8}
? multiply( 9, 9 ) ? multiply( 3.14159, 3.14159 ) ? multiply( a, b ) ? multiply( a, 7 ) ? multiply( 10.39564, b )</lang>
- Output:
81 9.869587728 {5,12,21,32} {7,14,21,28} {51.9782,62.37384,72.76948,83.16512}
F#
The default will be an integer function but you can specify other types as shown: <lang fsharp>let multiply x y = x * y // integer let fmultiply (x : float) (y : float) = x * y</lang>
Factor
<lang factor>: multiply ( a b -- a*b ) * ;</lang>
Falcon
<lang falcon>function sayHiTo( name )
> "Hi ", name
end</lang>
FALSE
<lang false>[*] {anonymous function to multiply the top two items on the stack} m: {binding the function to one of the 26 available symbol names} 2 3m;! {executing the function, yielding 6}</lang>
Fantom
<lang fantom>class FunctionDefinition {
public static Void main () { multiply := |Int a, Int b -> Int| { a * b } echo ("Multiply 2 and 4: ${multiply(2, 4)}") }
}</lang>
Fexl
<lang fexl>\multiply=(\x\y * x y)</lang> Or if I'm being cheeky: <lang fexl>\multiply=*</lang>
Forth
<lang forth>: fmultiply ( F: a b -- F: c ) F* ;
- multiply ( a b -- c ) * ;</lang>
Fortran
In FORTRAN 66 or later, define a function: <lang fortran>FUNCTION MULTIPLY(X,Y) REAL MULTIPLY, X, Y MULTIPLY = X * Y END</lang> In Fortran 95 or later, define an elemental function, so that this function can be applied to whole arrays as well as to scalar variables: <lang fortran>module elemFunc contains
elemental function multiply(x, y) real, intent(in) :: x, y real :: multiply multiply = x * y end function multiply
end module elemFunc</lang> <lang fortran>program funcDemo
use elemFunc real :: a = 20.0, b = 30.0, c real, dimension(5) :: x = (/ 1.0, 2.0, 3.0, 4.0, 5.0 /), y = (/ 32.0, 16.0, 8.0, 4.0, 2.0 /), z c = multiply(a,b) ! works with either function definition above z = multiply(x,y) ! element-wise invocation only works with elemental function
end program funcDemo</lang>
It is worth noting that Fortran can call functions (and subroutines) using named arguments; e.g. we can call multiply in the following way:
<lang fortran>c = multiply(y=b, x=a) ! the same as multiply(a, b)
z = multiply(y=x, x=y) ! the same as multiply(y, x)</lang>
(Because of commutativity property of the multiplication, the difference between multiply(x,y)
and multiply(y,x)
is not evident)
Also note that the function result can be declared with a different name within the routine: <lang fortran>module elemFunc contains
elemental function multiply(x, y) result(z) real, intent(in) :: x, y real :: z z = x * y end function multiply
end module elemFunc</lang>
Frink
<lang frink>multiply[x,y] := x*y</lang>
GAP
<lang gap>multiply := function(a, b)
return a*b;
end;</lang>
GML
In GML one can not define a function but in Game Maker there is a script resource, which is the equivalent of a function as defined here. Scripts can be exported to or imported from a text file with the following format: <lang GML>#define multiply a = argument0 b = argument1 return(a * b)</lang>
Gnuplot
<lang Gnuplot>multiply(x,y) = x*y
- then for example
print multiply(123,456)</lang>
Go
Function return types in Go are statically typed and never depend on argument types.
The return statement can contain an expression of the function return type: <lang go>func multiply(a, b float64) float64 {
return a * b
}</lang> Alternatively, if the return value is named, the return statement does not require an expression: <lang go>func multiply(a, b float64) (z float64) {
z = a * b return
}</lang>
Golfscript
<lang golfscript>{*}:multiply;</lang>
Groovy
<lang groovy>def multiply = { x, y -> x * y }</lang> Test Program: <lang groovy>println "x * y = 20 * 50 = ${multiply 20, 50}"</lang>
- Output:
x * y = 20 * 50 = 1000
Haskell
<lang haskell>multiply x y = x * y</lang> Alternatively, with help of auto-currying, <lang haskell>multiply = (*)</lang> You can use lambda-function <lang haskell>multiply = \ x y -> x*y</lang>
Haxe
<lang haxe>function multiply(x:Float, y:Float):Float{
return x * y;
}</lang>
HicEst
<lang hicest>FUNCTION multiply(a, b)
multiply = a * b
END</lang>
Icon and Unicon
<lang Icon>procedure multiply(a,b) return a * b end</lang>
IDL
The task description is unclear on what to do when the arguments to the function are non-scalar, so here's multiple versions: <lang idl>function multiply ,a,b
return, a* b
end</lang> If "a" and "b" are scalar, this will return a scalar. If they are arrays of the same dimensions, the result is an array of the same dimensions where each element is the product of the corresponding elements in "a" and "b".
Alternatively, there's this possibility: <lang idl>function multiply ,a,b
return, product([a, b])
end</lang> This will yield the same result for scalars, but if "a" and "b" are arrays it will return the product of all the elements in both arrays.
Finally, there's this option: <lang idl>function multiply ,a,b
return, a # b
end</lang> This will return a scalar if given scalars, if given one- or two-dimensional arrays it will return the matrix-product of these arrays. E.g. if given two three-element one-dimensional arrays (i.e. vectors), this will return a 3x3 matrix.
Inform 6
<lang inform6>[ multiply a b;
return a * b;
];</lang>
Inform 7
<lang inform7>To decide which number is (A - number) multiplied by (B - number): decide on A * B.</lang>
Io
<lang io>multiply := method(a,b,a*b)</lang>
IWBASIC
<lang IWBASIC> '1. Not Object Oriented Program
DECLARE Multiply(N1:INT,N2:INT),INT
DEF A,B:INT
A=2:B=2
OPENCONSOLE
PRINT Multiply(A,B)
'When compiled as a console only program, a press any key to continue is automatic. CLOSECONSOLE
END
SUB Multiply(N1:INT,N2:INT),INT
DEF Product:INT Product=N1*N2
RETURN Product ENDSUB
'Can also be written with no code in the subroutine and just RETURN N1*N2.
'2. Not Object Oriented Program Using A Macro
$MACRO Multiply (N1,N2) (N1*N2)
DEF A,B:INT
A=5:B=5
OPENCONSOLE
PRINT Multiply (A,B)
'When compiled as a console only program, a press any key to continue is automatic. CLOSECONSOLE
END
'3. In An Object Oriented Program
CLASS Associate 'functions/methods DECLARE Associate:'object constructor DECLARE _Associate:'object destructor '***Multiply declared*** DECLARE Multiply(UnitsSold:UINT),UINT 'members DEF m_Price:UINT DEF m_UnitsSold:UINT DEF m_SalesTotal:UINT ENDCLASS
DEF Emp:Associate
m_UnitsSold=10
Ass.Multiply(m_UnitsSold)
OPENCONSOLE
PRINT"Sales total: ",:PRINT"$"+LTRIM$(STR$(Emp.m_SalesTotal))
CLOSECONSOLE
END
'm_price is set in constructor SUB Associate::Multiply(UnitsSold:UINT),UINT
m_SalesTotal=m_Price*UnitsSold RETURN m_SalesTotal
ENDSUB
SUB Associate::Associate()
m_Price=10
ENDSUB
SUB Associate::_Associate() 'Nothing to cleanup ENDSUB
</lang>
J
<lang j>multiply=: *</lang> Works on conforming arrays of any rank (any number of dimensions, as long as the dimensions of one are a prefix of the dimensions of the other): atoms, lists, tables, etc.
Or, more verbosely (and a bit slower, though the speed difference should be unnoticeable in most contexts): <lang J>multiply=: dyad define
x * y
)</lang> Here we use an explicit definition (where the arguments are named) rather than a tacit version (where the arguments are implied). In explicit J verbs, x is the left argument and y is the right argument.
(Note, by the way, that explicit definitions are a subset of tacit definitions -- when the arguments are explicitly named they are still implied in the larger context containing the definition.)
Java
There are no global functions in Java. The equivalent is to define static methods in a class (here invoked as "Math.multiply(a,b)"). Overloading allows us to define the method for multiple types. <lang java>public class Math {
public static int multiply( int a, int b) { return a*b; } public static double multiply(double a, double b) { return a*b; }
}</lang>
JavaScript
ES1-*
Function Declaration <lang javascript>function multiply(a, b) {
return a*b;
}</lang>
ES3-*
Function Expression <lang javascript>var multiply = function(a, b) {
return a * b;
};</lang>
Named Function Expression <lang javascript>var multiply = function multiply(a, b) {
return a * b;
};</lang>
Method Definition <lang javascript>var o = {
multiply: function(a, b) { return a * b; }
};</lang>
ES5-*
Accessors <lang javascript>var o = {
get foo() { return 1; }, set bar(value) { // do things with value }
};</lang>
ES6-*
Arrow Function <lang javascript>var multiply = (a, b) => a * b; var multiply = (a, b) => { return a * b }; </lang>
Concise Body Method Definition <lang javascript>var o = {
multiply(a, b) { return a * b; }
};</lang>
Generator Functions <lang javascript>function * generator() {
yield 1;
}</lang>
Joy
<lang joy>DEFINE multiply == * .</lang>
jq
Example of a simple function definition:<lang jq>def multiply(a; b): a*b;</lang> Example of the definition of an inner function:<lang jq># 2 | generate(. * .) will generate 2, 4, 16, 256, ... def generate(f): def r: ., (f | r); r;</lang> The previous example (generate/1) also illustrates that a function argument can be a function or composition of functions. Here is another example:<lang jq>def summation(f): reduce .[] as $x (0; . + ($x|f));</lang> summation/1 expects an array as its input and takes a function, f, as its argument. For example, if the input array consists of JSON objects with attributes "h" and "w", then to compute SIGMA (h * w) we could simply write:<lang jq>summation( .h * .w)</lang>
Julia
General function definition <lang julia>function multiply(a::Number,b::Number)
return a*b
end</lang> Julia also supports "assignment" definition as a shorthand <lang julia>multiply(a,b) = a*b</lang> In addition, Julia support anonymous functions ("lambda" constructs): <lang julia>(a,b) -> a*b</lang>
Kaya
<lang kaya>program test;
// A function definition in Kaya: Int multiply(Int a, Int b) {
return a * b;
}
// And calling a function: Void main() {
putStrLn(string( multiply(2, 3) ));
}</lang>
Lasso
Lasso supports multiple dispatch — signature definitions determine which method will be invoked.
<lang Lasso>define multiply(a,b) => { return #a * #b }</lang>
As this function is so simple it can also be represented like so:
<lang Lasso>define multiply(a,b) => #a * #b</lang>
Using multiple dispatch, different functions will be invoked depending on the functions input.
<lang Lasso>// Signatures that convert second input to match first input define multiply(a::integer,b::any) => #a * integer(#b) define multiply(a::decimal,b::any) => #a * decimal(#b)
// Catch all signature define multiply(a::any,b::any) => decimal(#a) * decimal(#b)</lang>
LFE
<lang lisp> (defun mutiply (a b)
(* a b))
</lang>
Liberty BASIC
<lang lb>' define & call a function
print multiply( 3, 1.23456)
wait
function multiply( m1, m2)
multiply =m1 *m2
end function
end</lang>
Locomotive Basic
<lang locobasic>10 DEF FNmultiply(x,y)=x*y 20 PRINT FNmultiply(2,PI)</lang> Function names are always preceded by "FN" in Locomotive BASIC. Also, PI is predefined by the interpreter as 3.14159265.
Logo
<lang logo>to multiply :x :y
output :x * :y
end</lang>
LSE64
<lang lse64>multiply : * multiply. : *. # floating point</lang>
Lua
<lang Lua>function multiply( a, b )
return a * b
end</lang>
Lucid
<lang lucid>multiply(x,y) = x * y</lang>
M4
<lang M4>define(`multiply',`eval($1*$2)')
multiply(2,3)</lang>
Make
In makefile, a function may be defined as a rule, with recursive make used to retrieve the returned value. <lang make>A=1 B=1
multiply:
@expr $(A) \* $(B)</lang>
Invoking it <lang make>make -f mul.mk multiply A=100 B=3 > 300</lang> Using gmake, the define syntax is used to define a new function
<lang make>A=1 B=1
define multiply
expr $(1) \* $(2)
endef
do:
@$(call multiply, $(A), $(B))
|gmake -f mul.mk do A=5 B=3</lang>
Mathematica
There are two ways to define a function in Mathematica.
Defining a function as a transformation rule: <lang Mathematica>multiply[a_,b_]:=a*b</lang> Defining a pure function: <lang Mathematica>multiply=#1*#2&</lang>
Maxima
<lang Maxima>f(a, b):= a*b;</lang>
MAXScript
<lang maxscript>fn multiply a b = (
a * b
)</lang>
Mercury
<lang Mercury>% Module ceremony elided...
- - func multiply(integer, integer) = integer.
multiply(A, B) = A * B.</lang>
Metafont
Metafont has macros, rather than functions; through those the language can be expanded. According to the kind of macro we are going to define, Metafont has different ways of doing it. The one suitable for this task is called primarydef
.
<lang metafont>primarydef a mult b = a * b enddef;</lang>
<lang metafont>t := 3 mult 5; show t; end</lang>
The primarydef allows to build binary operators with the same priority as *. For a more generic macro, we can use instead
<lang metafont>def mult(expr a, b) = (a * b) enddef;
t := mult(2,3);
show t;
end</lang>
МК-61/52
ИП0 ИП1 * В/О
Function (subprogram) that multiplies two numbers. Parameters in registers Р0 and Р1, the result (return value) in register X. Commands ИП0 and ИП1 cause the contents of the corresponding registers in the stack, the more they multiplied (command *) and then code execution goes to the address from which the call subprogram (command В/О).
Modula-2
<lang modula2>PROCEDURE Multiply(a, b: INTEGER): INTEGER; BEGIN
RETURN a * b
END Multiply;</lang>
Modula-3
<lang modula3>PROCEDURE Multiply(a, b: INTEGER): INTEGER = BEGIN
RETURN a * b;
END Multiply;</lang>
MUMPS
<lang MUMPS>MULTIPLY(A,B);Returns the product of A and B
QUIT A*B</lang>
Neko
<lang Neko>var multiply = function(a, b) {
a * b
}
$print(multiply(2, 3))</lang>
Output: 6
Nemerle
<lang Nemerle>public Multiply (a : int, b : int) : int // this is either a class or module method {
def multiply(a, b) { return a * b } // this is a local function, can take advantage of type inference return multiply(a, b)
}</lang>
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary
pi = 3.14159265358979323846264338327950 radiusY = 10 in2ft = 12 ft2yds = 3 in2mm = 25.4 mm2m = 1 / 1000 radiusM = multiply(multiply(radiusY, multiply(multiply(ft2yds, in2ft), in2mm)), mm2m)
say "Area of a circle" radiusY "yds radius: " multiply(multiply(radiusY, radiusY), pi).format(3, 3) "sq. yds" say radiusY "yds =" radiusM.format(3, 3) "metres" say "Area of a circle" radiusM.format(3, 3)"m radius:" multiply(multiply(radiusM, radiusM), pi).format(3, 3)"m**2"
/**
* Multiplication function */
method multiply(multiplicand, multiplier) public static returns Rexx
product = multiplicand * multiplier return product</lang>
- Output:
Area of a circle 10 yds radius: 314.159 sq. yds 10 yds = 9.144 metres Area of a circle 9.144m radius: 262.677m**2
NewLISP
<lang NewLISP>> (define (my-multiply a b) (* a b)) (lambda (a b) (* a b)) > (my-multiply 2 3) 6</lang>
Nial
Using variables <lang nial>multiply is operation a b {a * b}</lang> Using it <lang nial>|multiply 2 3 =6</lang> Point free form <lang nial>mul is *</lang> Using it <lang nial>|mul 3 4 =12</lang> Nial also allows creation of operators <lang nial>multiply is op a b {a * b}</lang> Using it. <lang nial>|2 multiply 3 =6 |multiply 2 3 =6</lang> Since this is an array programming language, any parameters can be arrays too <lang nial>|mul 3 [1,2] =3 6 |mul [1,2] [10,20] =10 40</lang>
Nim
Nim has a magic variable, `result`, which can be used as a substitute for `return`. The `result` variable will be returned implicitly. <lang nim>proc multiply(a, b: Int): Int =
result = a * b</lang>
Here is the same function but with the use of the `return` keyword. <lang nim>proc multiply(a, b: Int): Int =
return a * b</lang>
The last statement in a function implicitly is the result value: <lang nim>proc multiply(a, b: Int): Int = a * b</lang>
Oberon-2
Oberon-2 uses procedures, and has a special procedure called a "Function Procedure" used to return a value. <lang oberon2>PROCEDURE Multiply(a, b: INTEGER): INTEGER;
BEGIN RETURN a * b; END Multiply;</lang>
Objeck
<lang objeck>function : Multiply(a : Float, b : Float) ~, Float {
return a * b;
}</lang>
OCaml
<lang ocaml>let int_multiply x y = x * y let float_multiply x y = x *. y</lang>
Octave
<lang octave>function r = mult(a, b)
r = a .* b;
endfunction</lang>
Oforth
Function #* is already defined : it removes 2 objects from the stack and returns on the stack the product of them.
If necessary, we can create a function with name multiply, but, it will just call *
<lang Oforth>func: multiply { * }</lang>
It is also possible to create a function with declared paramaters. In this case, if we define n parameters, n objects will be removed from the stack and stored into those parameters :
<lang Oforth>func: multiply2(a, b) { b a * }</lang>
A function return value (or values) is always what remains on the stack when the function ends. There is no syntax to define explicitely what is the return value(s) of a function.
OOC
<lang ooc> multiply: func (a: Double, b: Double) -> Double {
a * b
} </lang>
ooRexx
Internal Procedure
<lang rexx> SAY multiply(5, 6) EXIT
multiply:
PROCEDURE PARSE ARG x, y RETURN x*y</lang>
::Routine Directive
<lang rexx> say multiply(5, 6)
- routine multiply
use arg x, y return x *y
</lang>
OpenEdge/Progress
<lang Progress (Openedge ABL)>function multiply returns dec (a as dec , b as dec ):
return a * b .
end.</lang>
Oz
<lang oz>fun {Multiply X Y}
X * Y
end</lang> Or by exploiting first-class functions: <lang oz>Multiply = Number.'*'</lang>
PARI/GP
<lang parigp>multiply(a,b)=a*b;</lang>
or
<lang parigp>multiply=(a,b)->a*b;</lang>
Note that in both cases the ;
is part of the definition of the function, not of the function itself: it suppresses the output of the function body, but does not suppress the output of the function when called. To do that, either double the semicolon (which will suppress the output of both) or wrap in braces:
<lang parigp>multiply={(a,b)->a*b;}</lang>
which will return a function which calculates but does not return the product.
Pascal
(all versions and dialects) <lang pascal>function multiply(a,b: real): real; begin
multiply := a*b;
end;</lang>
Perl
The most basic form:
<lang perl>sub multiply { return $_[0] * $_[1] }</lang>
or simply:
<lang perl>sub multiply { $_[0] * $_[1] }</lang>
Arguments in Perl subroutines are passed in the @_
array, and they can be accessed directly, first one as $_[0]
, second one as $_[1]
, etc. When the above function is called with only one or no arguments then the missing ones have an undefined value which is converted to 0 in multiplication.
This is an example using subroutine prototypes: <lang perl>sub multiply( $$ ) {
my ($a, $b) = @_; return $a * $b;
}</lang>
The above subroutine can only be called with exactly two scalar values (two dollar signs in the signature) but those values may be not numbers or not even defined. The @_
array is unpacked into $a
and $b
lexical variables, which are used later.
The arguments can be automatically unpacked into lexical variables using the experimental signatures feature (in core as of 5.20): <lang perl>use experimental 'signatures'; sub multiply ($x, $y) {
return $x * $y;
}</lang>
Perl 6
Without a signature:
<lang perl6>sub multiply { return @_[0] * @_[1]; }</lang>
The return is optional on the final statement, since the last expression would return its value anyway. The final semicolon in a block is also optional.
(Beware that a subroutine without an explicit signature, like this one, magically becomes variadic (rather than nullary) only if @_
or %_
appear in the body.) In fact, we can define the variadic version explicitly, which still works for two arguments:
<lang perl6>sub multiply { [*] @_ }</lang>
With formal parameters and a return type:
<lang perl6>sub multiply (Rat $a, Rat $b --> Rat) { $a * $b }</lang>
Same thing:
<lang perl6>sub multiply (Rat $a, Rat $b) returns Rat { $a * $b }
my Rat sub multiply (Rat $a, Rat $b) { $a * $b }</lang>
It is possible to define a function in "lambda" notation and then bind that into a scope, in which case it works like any function:
<lang perl6>my &multiply := -> $a, $b { $a * $b };</lang>
Another way to write a lambda is with internal placeholder parameters:
<lang perl6>my &multiply := { $^a * $^b };</lang>
(And, in fact, our original @_ above is just a variadic self-declaring placeholder argument. And the famous Perl "topic", $_, is just a self-declared parameter to a unary block.)
You may also curry both built-in and user-defined operators by supplying a * (known as "whatever") in place of the argument that is not to be curried: <lang perl6>my &multiply := * * *;</lang> This is not terribly readable in this case due to the visual confusion between the whatever star and the multiplication operator, but Perl knows when it's expecting terms instead of infixes, so only the middle star is multiplication. It tends to work out much better with other operators. In particular, you may curry a cascade of methods with only the original invocant missing: <lang perl6>@list.grep( *.substr(0,1).lc.match(/<[0..9 a..f]>/) )</lang> This is equivalent to: <lang perl6>@list.grep( -> $obj { $obj.substr(0,1).lc.match(/<[0..9 a..f]>/) )</lang>
PHL
<lang phl>@Integer multiply(@Integer a, @Integer b) [ return a * b; ]</lang>
PHP
<lang php>function multiply( $a, $b ) {
return $a * $b;
}</lang>
PicoLisp
<lang PicoLisp>(de multiply (A B)
(* A B) )</lang>
Pike
<lang pike>int multiply(int a, int b){
return a * b;
}</lang>
PL/I
<lang pli>PRODUCT: procedure (a, b) returns (float);
declare (a, b) float; return (a*b);
end PRODUCT;</lang>
PL/SQL
<lang plsql>FUNCTION multiply(p_arg1 NUMBER, p_arg2 NUMBER) RETURN NUMBER IS
v_product NUMBER;
BEGIN
v_product := p_arg1 * p_arg2; RETURN v_product;
END;</lang>
Pop11
<lang pop11>define multiply(a, b);
a * b
enddefine;</lang>
PostScript
Inbuilt: <lang postscript>3 4 mul</lang> Function would be: <lang postscript>/multiply{
/x exch def /y exch def x y mul =
}def</lang>
PowerShell
The most basic variant of function definition would be the kind which uses positional parameters and therefore doesn't need to declare much: <lang powershell>function multiply {
return $args[0] * $args[1]
}</lang> Also, the return statement can be omitted in many cases in PowerShell, since every value that "drops" out of a function can be used as a "return value": <lang powershell>function multiply {
$args[0] * $args[1]
}</lang> Furthermore, the function arguments can be stated and named explicitly: <lang powershell>function multiply ($a, $b) {
return $a * $b
}</lang> There is also an alternative style for declaring parameters. The choice is mostly a matter of personal preference: <lang powershell>function multiply {
param ($a, $b) return $a * $b
}</lang> And the arguments can have an explicit type: <lang powershell>function multiply ([int] $a, [int] $b) {
return $a * $b
}</lang>
Prolog
Prolog, as a logic programming languages, does not have user-supplied functions available. It has only predicates; statements which are "true" or "false". In cases where values have to be "returned" a parameter is passed in that is unified with the result. In the following predicate the parameter "P" (for "Product") is used in this role. The following code will work in any normal Prolog environment (but not in things like Turbo Prolog or Visual Prolog or their ilk): <lang Prolog>multiply(A, B, P) :- P is A * B.</lang> This is what it looks like in use: <lang Prolog>go :-
multiply(5, 2, P), format("The product is ~d.~n", [P]).</lang>
This can be a little bit jarring for those used to languages with implicit return values, but it has its advantages. For example unit testing of such a predicate doesn't require special frameworks to wrap the code: <lang Prolog>test_multiply :-
multiply(5, 2, 10), % this will pass multiply(3, 4, 11). % this will not pass</lang>
Still, the lack of user-defined functions remains an annoyance.
Prolog, however, is a remarkably malleable language and through its term re-writing capabilities the function-style approach could be emulated. The following code relies on the function_expansion pack (separately installed through the packs system) for SWI-Prolog. Similar code could be made in any Prolog implementation, however. <lang Prolog>:- use_module(library(function_expansion)).
user:function_expansion(multiply(A, B), P, P is A * B). % "function" definition
go :-
format("The product is ~d.~n", [multiply(5, 2)]).</lang>
While the function definition is perhaps a bit more involved, the function use is now pretty much the same as any other language people are used to. The "magic" is accomplished by the compiler rewriting the go/0
term into the following code:
<lang Prolog>go :-
A is 5*2, format('The product is ~d.~n', [A]).</lang>
PureBasic
<lang PureBasic>Procedure multiply(a,b)
ProcedureReturn a*b
EndProcedure</lang>
Python
Function definition: <lang python>def multiply(a, b):
return a * b</lang>
Lambda function definition: <lang python>multiply = lambda a, b: a * b</lang> A callable class definition allows functions and classes to use the same interface: <lang python>class Multiply:
def __init__(self): pass def __call__(self, a, b): return a * b
multiply = Multiply() print multiply(2, 4) # prints 8</lang> (No extra functionality is shown in this class definition).
Q
<lang q>multiply:{[a;b] a*b}</lang> or <lang q>multiply:{x*y}</lang> or <lang q>multiply:*</lang> Using it <lang q>multiply[2;3]
6</lang>
QueebaScript
<lang queebascript><queebascript.Begin> function multiply([VAR]a, [VAR]b) {
return a * b;
}</lang>
R
<lang rsplus>mult <- function(a,b) a*b</lang> In general: <lang rsplus>mult <- function(a,b) {
a*b # or: # return(a*b)
}</lang>
Racket
A simple function definition that takes 2 arguments. <lang racket> (define (mutiply a b)
(* a b))
</lang>
Using an explicit lambda is completely equivalent: <lang racket> (define multiply (lambda (a b) (* a b))) </lang>
Raven
<lang raven>define multiply use a, b
a b *</lang>
Or optional infix: <lang raven>define multiply use a, b
(a * b)</lang>
Or skip named vars: <lang raven>define multiply *</lang>
REALbasic
<lang vb> Function Multiply(a As Integer, b As Integer) As Integer
Return a * b
End Function </lang>
REBOL
REBOL actually already has a function called 'multiply', which is a native compiled function. However, since it's not protected, I can easily override it: <lang REBOL>multiply: func [a b][a * b]</lang>
Retro
<lang Retro>: multiply ( nn-n ) * ;</lang>
REXX
exactitudeness
<lang rexx>multiply: return arg(1) * arg(2) /*return the product of the two arguments.*/</lang>
cleaner display
Because REXX will return the same precision as the multiplicands, we can do some beautification with the resultant product.
I.E.: 3.0 * 4.00 yields the product: 12.000
This version eliminates the .000 from the product.
<lang rexx>multiply: return arg(1) * arg(2) / 1 /*return with a normalized product of 2 args. */</lang>
RLaB
In RLaB the functions can be built-in (compiled within RLaB, or part of the shared object library that is loaded per request of user), or user (written in RLaB script). Consider an example: <lang RLaB>>> class(sin) function >> type(sin) builtin</lang> Functions are a data class on their own, or they can be member of a list (associative array).
1. user function specified from built-in functions, here basic addition <lang RLaB>f = function(x, y) {
return x + y;
};
>> class(f) function >> type(f) user</lang>
2. function can be member of a list (associative array) <lang RLaB>somelist = <<>>; somelist.f = function(x, y) {
rval = x + y; return rval;
};</lang>
3. user function which uses a function that is specified as a member of some list, here we use somelist from above: <lang RLaB>g = function(x, y) {
global(somelist); rval = x * somelist.f(x, 2*y); return rval;
};</lang>
Ruby
<lang ruby>def multiply(a, b)
a * b
end</lang>
Rust
<lang rust>fn multiply(a: i32, b: i32) -> i32 {
a * b
}</lang>
Sather
<lang sather>class MAIN is
-- we cannot have "functions" (methods) outside classes mult(a, b:FLT):FLT is return a*b; end;
main is #OUT + mult(5.2, 3.4) + "\n"; end;
end;</lang>
Scala
<lang scala>def multiply(a: Int, b: Int) = a * b</lang>
Scheme
<lang scheme>(define multiply *)</lang> Alternately, <lang scheme>(define (multiply a b)
(* a b))</lang>
Seed7
<lang seed7>const func float: multiply (in float: a, in float: b) is
return a * b;</lang>
Sidef
<lang ruby>func multiply(a, b) {
a * b;
};</lang>
Slate
<lang slate>define: #multiply -> [| :a :b | a * b].</lang> or using a macro: <lang slate>define: #multiply -> #* `er.</lang> The block may also be installed as a method like so: <lang slate>a@(Number traits) multiplyBy: b@(Number traits) [a * b].</lang> or more explicitly (without sugar): <lang slate>[| :a :b | a * b] asMethod: #multipleBy: on: {Number traits. Number traits}.</lang>
Smalltalk
<lang smalltalk>|mul| mul := [ :a :b | a * b ].</lang>
SNOBOL4
<lang snobol4> define('multiply(a,b)') :(mul_end) multiply multiply = a * b :(return) mul_end
- Test
output = multiply(10.1,12.2) output = multiply(10,12)
end</lang>
- Output:
123.22 120
SNUSP
For expediency, the function is adding three values, instead of multiplying two values. Another function, atoi (+48) is called before printing the result. <lang snusp>+1>++2=@\=>+++3=@\==@\=.=# prints '6'
| | \=itoa=@@@+@+++++# \=======!\==!/===?\<# \>+<-/</lang>
SPARK
The function definition (multiplies two standard Integer): <lang Ada>package Functions is
function Multiply (A, B : Integer) return Integer; --# pre A * B in Integer; -- See note below --# return A * B; -- Implies commutativity on Multiply arguments
end Functions;</lang> Note: how do you ensure then “A * B in Integer” ? Either with a proof prior to Multiply invokation or using another form of Multiply where input A and B would be restricted to a range which ensures the resulting product is always valid. Exemple : <lang Ada>type Input_Type is range 0 .. 10; type Result_Type is range 0 .. 100;</lang> and had a version of Multiply using these types. On the other hand, if arguments of Multiply are constants, this is provable straight away.
The Multiply's implementation: <lang Ada>package body Functions is
function Multiply (A, B : Integer) return Integer is begin return A * B; end Multiply;
end Functions;</lang>
Standard ML
<lang ocaml>val multiply = op *</lang> Equivalently, <lang ocaml>fun multiply (x, y) = x * y</lang> Curried form: <lang ocaml>fun multiply x y = x * y</lang>
Swift
<lang swift>func multiply(a: Double, b: Double) -> Double {
return a * b
}</lang>
Tcl
Strictly as described in the task: <lang tcl>proc multiply { arg1 arg2 } {
return [expr {$arg1 * $arg2}]
}</lang>
You can also create functions that work directly inside expressions. This is done by creating the command with the correct name (that is, in the tcl::mathfunc namespace): <lang tcl>proc tcl::mathfunc::multiply {arg1 arg2} {
return [expr {$arg1 * $arg2}]
}
- Demonstrating...
if {multiply(6, 9) == 42} {
puts "Welcome, Citizens of Golgafrincham from the B-Ark!"
}</lang>
TI-89 BASIC
<lang ti89b>multiply(a, b) Func
Return a * b
EndFunc</lang>
Toka
<lang toka>[ ( ab-c ) * ] is multiply</lang>
TXR
In TXR, there are pattern functions which are predicates that perform pattern matching and variable capture. A call to this type of function call can specify unbound variables. If the function succeeds, it can establish bindings for those variables.
Here is how to make a pattern function that multiplies, and call it. To multiply the numbers, we break out of the pattern language and invoke Lisp evaluation: @(* a b)
<lang txr>@(define multiply (a b out))
@(bind out @(* a b))
@(end)
@(multiply 3 4 result)</lang>
$ txr -B multiply.txr result="12"
In the embedded Lisp dialect, it is possible to write an ordinary function that returns a value: <lang txr>@(do (defun mult (a b) (* a b))
(put-line `3 * 4 = @(mult 3 4)`))</lang>
$ txr multiply2.txr 3 * 4 = 12
UNIX Shell
Note that in the Unix shell, function definitions do not include any argument specifications within the parentheses. Instead arguments to functions are obtained using the positional parameters.
<lang bash>multiply() {
# There is never anything between the parentheses after the function name # Arguments are obtained using the positional parameters $1, and $2 # The return is given as a parameter to the return command return `expr "$1" \* "$2"` # The backslash is required to suppress interpolation
}
- Call the function
multiply 3 4 # The function is invoked in statement context echo $? # The dollarhook special variable gives the return value</lang>
return an exit code <lang bash>multiply() {
return $(($1 * $2))
}
multiply 5 6 echo $?</lang> echo the result <lang bash>multiply() {
echo -n $(($1 * $2))
}
echo $(multiply 5 6)</lang>
Ursala
Functions are declared with an equals sign like constants of any other type.
They may be specified by lambda abstraction, with dummy variables in double quotes, or in point-free form, or any combination. The way multiplication is defined depends on the type of numbers being multiplied. For this example, numbers in standard IEEE double precision are assumed, and the multiply function is defined in terms of the system library function, called using the syntax math..mul
.
This is the definition in point free form,
<lang Ursala>multiply = math..mul</lang>
this is the definition using lambda abstraction
<lang Ursala>multiply = ("a","b"). math..mul ("a","b")</lang>
and this is the definition using pattern matching.
<lang Ursala>multiply("a","b") = math..mul ("a","b")</lang>
V
V uses stack for input arguments and '.' is a word that takes a quote and binds the first word to the sequence of actions supplied in the quote. <lang v>[multiply *].</lang> Using it <lang v>2 3 multiply =6</lang> V also allows internal bindings. <lang v>[multiply
[a b] let a b *].</lang>
VBScript
<lang vb>function multiply( multiplicand, multiplier )
multiply = multiplicand * multiplier
end function</lang> Usage: <lang vb>dim twosquared twosquared = multiply(2, 2)</lang>
Visual Basic .NET
<lang vbnet>Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer
Return a * b
End Function</lang> Call the function <lang vbnet>Multiply(1, 1)</lang>
Wart
A straightforward way to say how calls of the form (multiply a b)
are translated:
<lang python>def (multiply a b)
a*b</lang>
<lang python>(multiply 3 4) => 12</lang>
Functions can also use keyword args.
<lang python>(multiply 3 :a 4) # arg order doesn't matter here, but try subtract instead => 12</lang>
Finally, we can give params better keyword args using aliases:
<lang python>def (multiply a b|by)
(* a b)</lang>
<lang python>multiply 3 :by 4 => 12</lang>
X86 Assembly
X86 Assembly doesn't really have functions. Instead, it has labels that are called. Function arguments can be pushed onto the stack prior to calling or passed to the function in registers. The system will usually have some sort of calling conventions to facilitate inter-operation between languages.
Unix
Function definition and calling conventions on a Unix-like system are specified in the book "System V Application Binary Interface: Intel 386 Architecture Processor Supplement" (from SCO at archive.org). These are the conventions used by the C language and also most other languages.
The stack, for two 32-bit integer parameters, is
[esp+8]
second parameter[esp+4]
first parameter[esp]
return address
The return value is left in the eax
register. ecx
and edx
are "scratch" registers meaning the called routine doesn't need to preserve their values. (In the code below edx is clobbered.)
The following is Unix-style "as" assembler syntax (including GNU as). The resulting function can be called from C with multiply(123,456)
.
<lang asm> .text
.globl multiply .type multiply,@function
multiply:
movl 4(%esp), %eax mull 8(%esp) ret</lang>
The .type
directive is important for code which will go into a shared library. You can get away without it for a static link. It ensures the linker knows to dispatch calls from the mainline to the function via a PLT entry. (If omitted the code is copied at runtime into some mainline space. Without a .size
directive only 4 bytes will be copied.)
NASM
<lang asm>section .text global _start
_multiply_regs:
mul ebx mov eax, ebx ret
_multiply_stack:
enter 2,0 mov eax, [esp+4] mov ebx, [esp+8] mul ebx mov eax, ebx leave ret
_start:
mov ax, 6 ;The number to multiply by mov ebx, 16 ;base number to multiply. call _multiply_regs push 6 push 16 call _multiply_stack</lang>
MASM
However, in MASM we do have function statements due to the preprocessor.
<lang asm>multiply proc arg1:dword, arg2:dword
mov eax, arg1 mov ebx, arg2 mul ebx mov eax, ebx ret
multiply endp</lang> Then to call it. <lang asm>invoke multiply, 6, 16
- or..
push 16 push 6 call multiply</lang> Return values are usually put into the register EAX. This, of course is not a must it's simply that it's somewhat of a unofficial standard. For example, C/C++ preprocessors/compilers will translate "return value" into "mov eax, value" followed by the return to caller instruction "ret".
uBasic/4tH
In uBasic you can turn any subroutine into a function with the FUNC() function. It takes one argument, which is the label. Arguments are optional. <lang>PRINT FUNC (_Multiply (2,3)) END
_Multiply PARAM (2) RETURN (a@ * b@)</lang>
XPL0
<lang XPL0>func Multiply(A, B); \the characters in parentheses are only a comment int A, B; \the arguments are actually declared here, as integers return A*B; \the default (undeclared) function type is integer
\no need to enclose a single statement in brackets
func real FloatMul(A, B); \floating point version real A, B; \arguments are declared here as floating point (doubles) return A*B;</lang>
XSLT
Templates are the closest things XSLT has to user defined functions. They can be declared to be called by name and/or to be applied to all nodes in a matching set and given "mode". Both types of template can take named parameters with default values. Templates also have a "context" node used as the base of XPath expressions (kind of like an implied "this" of an object's method). <lang xslt><xsl:template name="product">
<xsl:param name="a" select="2"/> <xsl:param name="b" select="3"/> <fo:block>product = <xsl:value-of select="$a * $b"/></fo:block>
</xsl:template>
<xsl:call-template name="product">
<xsl:with-param name="a">4</xsl:with-param> <xsl:with-param name="b">5</xsl:with-param>
</xsl:call-template></lang>
<xsl:call-template name="product"/> <-- using default parameters of 2 and 3 -->
Yorick
<lang yorick>func multiply(x, y) {
return x * y;
}</lang> Example of interactive usage:
> multiply(2, 4.5) 9
zkl
<lang zkl>fcn multiply(x,y){x*y}</lang> <lang zkl>fcn(x,y){x*y}(4.5,3) // --> 13.5</lang> Since all functions are vararg:<lang zkl>fcn multiply{vm.arglist.reduce('*)} multiply(1,2,3,4,5) //--> 120</lang> Operators are first class objects so:<lang zkl>var mul=Op("*"); mul(4,5) //-->20</lang>
ZX Spectrum Basic
On the ZX Spectrum, function names are limited to one letter. Note that the function becomes effective as soon as it is entered into the program, and does not need to be run <lang zxbasic>10 PRINT FN m(3,4): REM call our function to produce a value of 12 20 STOP 9950 DEF FN m(a,b)=a*b</lang>
- Programming Tasks
- Basic language learning
- Functions and subroutines
- Simple
- 8051 Assembly
- ACL2
- ActionScript
- Ada
- Aime
- ALGOL 68
- ALGOL W
- AmigaE
- APL
- AppleScript
- Applesoft BASIC
- Argile
- AutoHotkey
- AutoIt
- AWK
- Axe
- BASIC
- Batch File
- BBC BASIC
- Bc
- Boo
- Bracmat
- Brat
- C
- C sharp
- ChucK
- C++
- Clay
- Clojure
- COBOL
- Coco
- CoffeeScript
- ColdFusion
- Common Lisp
- Creative Basic
- D
- Dc
- Delphi
- Déjà Vu
- DWScript
- E
- Efene
- Eiffel
- Ela
- Elixir
- Emacs Lisp
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Falcon
- FALSE
- Fantom
- Fexl
- Forth
- Fortran
- Frink
- GAP
- GML
- Gnuplot
- Go
- Golfscript
- Groovy
- Haskell
- Haxe
- HicEst
- Icon
- Unicon
- IDL
- Inform 6
- Inform 7
- Io
- IWBASIC
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- Kaya
- Lasso
- LFE
- Liberty BASIC
- Locomotive Basic
- Logo
- LSE64
- Lua
- Lucid
- M4
- Make
- Mathematica
- Maxima
- MAXScript
- Mercury
- Metafont
- МК-61/52
- Modula-2
- Modula-3
- MUMPS
- Neko
- Nemerle
- NetRexx
- NewLISP
- Nial
- Nim
- Oberon-2
- Objeck
- OCaml
- Octave
- Oforth
- OOC
- OoRexx
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHL
- PHP
- PicoLisp
- Pike
- PL/I
- PL/SQL
- Pop11
- PostScript
- PowerShell
- Prolog
- PureBasic
- Python
- Q
- QueebaScript
- R
- Racket
- Raven
- REALbasic
- REBOL
- Retro
- REXX
- RLaB
- Ruby
- Rust
- Sather
- Scala
- Scheme
- Seed7
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- SNUSP
- SPARK
- Standard ML
- Swift
- Tcl
- TI-89 BASIC
- Toka
- TXR
- UNIX Shell
- Ursala
- V
- VBScript
- Visual Basic .NET
- Wart
- X86 Assembly
- UBasic/4tH
- XPL0
- XSLT
- Yorick
- Zkl
- ZX Spectrum Basic
- GUISS/Omit