Function definition: Difference between revisions
Add Brat solution |
m Semi-automated edit: Bash -> UNIX Shell |
||
Line 94: | Line 94: | ||
print mul(5, 6) |
print mul(5, 6) |
||
}</lang> |
}</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
Line 143: | Line 128: | ||
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). |
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). |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 164: | Line 160: | ||
Of course, both inline and template may be combined (the <tt>inline</tt> then has to follow the <tt>template<...></tt>), but since templates have to be in the header anyway (while the standard allows them to be compiled separately using the keyword <tt>export</tt>, almost no compiler implements that), the compiler usually can inline the template even without the keyword. |
Of course, both inline and template may be combined (the <tt>inline</tt> then has to follow the <tt>template<...></tt>), but since templates have to be in the header anyway (while the standard allows them to be compiled separately using the keyword <tt>export</tt>, almost no compiler implements that), the compiler usually can inline the template even without the keyword. |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 256: | Line 241: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
<lang erlang>multiply(A,B) -> A*B.</lang> |
<lang erlang>multiply(A,B) -> A*B.</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Line 320: | Line 310: | ||
end function multiply |
end function multiply |
||
end module elemFunc</lang> |
end module elemFunc</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|GML}}== |
=={{header|GML}}== |
||
Line 356: | Line 341: | ||
multiply = a * b |
multiply = a * b |
||
END</lang> |
END</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
Line 382: | Line 373: | ||
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. |
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. |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
Line 430: | Line 415: | ||
output :x * :y |
output :x * :y |
||
end</lang> |
end</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<lang Lua>function multiply( a, b ) |
<lang Lua>function multiply( a, b ) |
||
Line 437: | Line 426: | ||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
<lang lucid>multiply(x,y) = x * y</lang> |
<lang lucid>multiply(x,y) = x * y</lang> |
||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|M4}}== |
=={{header|M4}}== |
||
Line 957: | Line 942: | ||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
<lang toka>[ ( ab-c ) * ] is multiply</lang> |
<lang toka>[ ( ab-c ) * ] is multiply</lang> |
||
⚫ | |||
{{works with|Bash}} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
Revision as of 15:27, 17 January 2011
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).
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> 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>
ALGOL 68
<lang algol68>PROC multiply = ( LONG REAL a, b ) LONG REAL: (
a * b
)</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
multiply ← ×
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>
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 mul(a, b) {
return a*b
} BEGIN {
print mul(5, 6)
}</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>
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). This is useful for less complex function as they won't take up any extra memory.
<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>
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.
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>
Common Lisp
<lang lisp>(defun multiply (a b)
(* a b))
(multiply 2 3)</lang>
D
<lang d>double multiply(double a, double b) {
return a * b;
}</lang> or templated one: <lang d>T multiply(T)(T a, T b) {
return a * b;
}</lang>
Compile-time evaluation
Function "multiply" can be evaluated at compile time if appears in a context where only compile-time constant is valid: <lang d>const result = multiply(2, 3); // Evaluated at compile time writefln("2 * 3 = ", result);</lang> Compile-time multiplication can also be done using template: <lang d>template multiply(int a, int b) {
const multiply = a * b;
}</lang> Use it like this: <lang d>import std.metastrings; pragma (msg, ToString!(multiply!(2, 3))); // Prints "6" during program compilation</lang>
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>
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>
Erlang
<lang erlang>multiply(A,B) -> A*B.</lang>
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>
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>
GML
In GML one can not define a function but in Game Maker there is a script resource, which is the equivelant 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>
Go
<lang go>func multiply(a float64, b float64) float64 {
return a * b
}</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 = (*)</lang> Alternatively, <lang haskell>multiply = \ x y -> 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 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>
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):
<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
<lang javascript>function multiply(a,b) { return a*b }</lang>
Joy
<lang joy>DEFINE multiply == * .</lang>
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>
MATLAB
<lang MATLAB>function C = multiply(A,B)
C = A*B;
end</lang>
MAXScript
<lang maxscript>fn 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>
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>
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>
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 = ( * ) let float_multiply = ( *. )</lang> Alternatively, <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>
OpenEdge/Progress
<lang openedge>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>multiply(a,b)=a*b;</lang>
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 signatures module: <lang perl>use signatures; sub multiply ($x, $y) {
return $x * $y;
}</lang>
Perl 6
Without parameters:
<lang perl6>sub multiply { return @_[0] * @_[1]; }</lang>
(Beware that a subroutine without an explicit signature, like this one, magically becomes variadic (rather than nullary) only if @_
or %_
appear in the body.)
With formal parameters and a return type: <lang perl6>sub multiply (Int $a, Int $b --> Int) { $a * $b }</lang> (Without an explicit return, a subroutine returns the value of the last expression evaluated. Also, the final semicolon in a block is optional.)
Same thing: <lang perl6>sub multiply (Int $a, Int $b) returns Int { $a * $b }</lang>
Naming the function via binding, and with placeholder parameters: <lang perl6>&multiply := { $^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 PL/I> 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> 3 4 mul </lang> Function would be: <lang> /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>
PureBasic
<lang PureBasic>Procedure multiply(a,b)
ProcedureReturn a*b
EndProcedure</lang>
Python
Named function: <lang python>def multiply(a, b):
return a * b</lang>
Unnamed function: <lang python>multiply = lambda a, b: a * b</lang>
A callable class, which may be useful to allow both simple functions and complex classes to use the same interface: <lang python>class Multiplier:
callcount = 0 def __init__(self, a=1): self.multiplicand = a def __call__(self, a, b): Multiplier.callcount += 1 return self.multiplicand * a
m4 = Multiplier(4) m2 = Multiplier(2) print m4(2), m4(4), m4(12), m2(2), m2(3)
- >>> 4 8 48 4 6</lang>
(This trite example implements a simplistic "curried" multiplication class ... but also keeps track of the total number of times any instance has been called as a function. I can conceive of no useful application for it).
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>
R
<lang R>mult <- function(a,b) a*b</lang>
In general <lang R>mult <- function(a,b) {
a*b # or: # return(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>
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
<lang rexx> multiply: return arg(1)*arg(2) </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>
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>
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 sml>val multiply = op *</lang> Equivalently, <lang sml>fun multiply (x, y) = x * y</lang> Curried form: <lang sml>fun multiply x y = x * y</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>
UNIX Shell
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>
X86 Assembly
X86 Assembly doesn't really have functions. rather labels that are called. Function arguments can be pushed onto the stack prior to calling or passed to the function in registers.
<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>
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".
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
- Programming Tasks
- Basic language learning
- ActionScript
- Ada
- ALGOL 68
- AmigaE
- APL
- AppleScript
- Argile
- AutoHotkey
- AutoIt
- AWK
- BASIC
- Brat
- C
- C sharp
- C++
- Clojure
- Common Lisp
- D
- Dc
- E
- Efene
- Erlang
- F Sharp
- Factor
- Falcon
- FALSE
- Forth
- Fortran
- GML
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- Inform 7
- Io
- J
- Java
- JavaScript
- Joy
- Logo
- LSE64
- Lua
- Lucid
- M4
- Make
- MATLAB
- MAXScript
- Metafont
- Modula-2
- Modula-3
- MUMPS
- Nial
- Oberon-2
- Objeck
- OCaml
- Octave
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PL/SQL
- Pop11
- PostScript
- PowerShell
- PureBasic
- Python
- Q
- R
- Raven
- REBOL
- Retro
- REXX
- RLaB
- Ruby
- Sather
- Scala
- Scheme
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- SNUSP
- SPARK
- Standard ML
- Tcl
- TI-89 BASIC
- Toka
- UNIX Shell
- Ursala
- V
- VBScript
- Visual Basic .NET
- X86 Assembly
- XSLT
- Yorick