Function definition: Difference between revisions
m →ES6-* |
|||
(64 intermediate revisions by 36 users not shown) | |||
Line 17: | Line 17: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
Function definition: |
Function definition: |
||
< |
<syntaxhighlight lang="11l">F multiply(a, b) |
||
R a * b</ |
R a * b</syntaxhighlight> |
||
Lambda function definition: |
Lambda function definition: |
||
< |
<syntaxhighlight lang="11l">V multiply = (a, b) -> a * b</syntaxhighlight> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Linkage conventions are: register 1 : the parameter list, register 0 : the return value, |
Linkage conventions are: register 1 : the parameter list, register 0 : the return value, |
||
and register 14 : the return address. |
and register 14 : the return address. |
||
< |
<syntaxhighlight lang="360asm">DEFFUN CSECT |
||
USING DEFFUN,R13 |
USING DEFFUN,R13 |
||
SAVEAREA B PROLOG-SAVEAREA(R15) |
SAVEAREA B PROLOG-SAVEAREA(R15) |
||
Line 62: | Line 62: | ||
Z DS F |
Z DS F |
||
YREGS |
YREGS |
||
END DEFFUN</ |
END DEFFUN</syntaxhighlight> |
||
=={{header|6502 Assembly}}== |
=={{header|6502 Assembly}}== |
||
As with other low-level languages, 6502 assembler has subroutines rather than functions in the strict sense. This implementation of <tt>MULTIPLY</tt> behaves rather like a function, however: it expects two 'parameters' to be passed in the index registers <tt>X</tt> and <tt>Y</tt> and it returns the answer in the accumulator. Note that the 6502 has no <tt>MUL</tt> instruction, so multiplication is carried out by repeated addition. |
As with other low-level languages, 6502 assembler has subroutines rather than functions in the strict sense. This implementation of <tt>MULTIPLY</tt> behaves rather like a function, however: it expects two 'parameters' to be passed in the index registers <tt>X</tt> and <tt>Y</tt> and it returns the answer in the accumulator. Note that the 6502 has no <tt>MUL</tt> instruction, so multiplication is carried out by repeated addition. |
||
< |
<syntaxhighlight lang="asm6502">MULTIPLY: STX MULN ; 6502 has no "acc += xreg" instruction, |
||
TXA ; so use a memory address |
TXA ; so use a memory address |
||
MULLOOP: DEY |
MULLOOP: DEY |
||
Line 73: | Line 73: | ||
CPY #$01 |
CPY #$01 |
||
BNE MULLOOP |
BNE MULLOOP |
||
RTS</ |
RTS</syntaxhighlight> |
||
An alternative implementation that multiplies A by X and checks if A/X is zero. |
An alternative implementation that multiplies A by X and checks if A/X is zero. |
||
< |
<syntaxhighlight lang="asm6502">; https://skilldrick.github.io/easy6502/ |
||
; Multiplies A by X |
; Multiplies A by X |
||
Line 96: | Line 96: | ||
MAIN: LDA #50 |
MAIN: LDA #50 |
||
LDX #5 |
LDX #5 |
||
JSR MULTIPLY</ |
JSR MULTIPLY</syntaxhighlight> |
||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
What values are returned (if any) and where they are returned, will depend on the calling convention used. Code written by a C compiler will typically pass parameters onto the stack and use a "frame pointer" to reference them. For this simple example, the operands will be passed into the function using the registers <code>D0</code> and <code>D1</code>, and the output will be in <code>D0</code>. A function is called by using <code>JSR foo</code> where <code>foo</code> is a labeled section of code or a 24-bit memory address. Execution will continue along starting at that address, until an <code>RTS</code> is encountered, at which point the return address will be popped off the stack into the program counter. |
What values are returned (if any) and where they are returned, will depend on the calling convention used. Code written by a C compiler will typically pass parameters onto the stack and use a "frame pointer" to reference them. For this simple example, the operands will be passed into the function using the registers <code>D0</code> and <code>D1</code>, and the output will be in <code>D0</code>. A function is called by using <code>JSR foo</code> where <code>foo</code> is a labeled section of code or a 24-bit memory address. Execution will continue along starting at that address, until an <code>RTS</code> is encountered, at which point the return address will be popped off the stack into the program counter. |
||
< |
<syntaxhighlight lang="68000devpac">MOVE.L D0,#$0200 |
||
MOVE.L D1,#$0400 |
MOVE.L D1,#$0400 |
||
Line 113: | Line 113: | ||
MULU D0,D1 |
MULU D0,D1 |
||
RTS |
RTS |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|8051 Assembly}}== |
=={{header|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. |
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. |
||
< |
<syntaxhighlight lang="asm">ORG RESET |
||
mov a, #100 |
mov a, #100 |
||
mov b, #10 |
mov b, #10 |
||
Line 129: | Line 129: | ||
multiply: |
multiply: |
||
mul ab |
mul ab |
||
ret</ |
ret</syntaxhighlight> |
||
=={{header|8086 Assembly}}== |
|||
A function is nothing more than a named section of code. A <code>CALL</code> instruction will push the current value of the instruction pointer and then set the instruction pointer to that address. Execution will continue forward until a <code>RET</code> statement is encountered, at which point the top of the stack is popped into the instruction pointer register. Note that the <code>RET</code> statement assumes that the top of the stack contains the actual return address, even though in reality this may not be the case. There is no validation that the return address is correct! This is why it's important for the assembly programmer to ensure the stack is balanced at all times, otherwise your program will go running off to who knows where. |
|||
It's important to remember that, unlike other languages, execution of assembly code (and this is true for all assembly languages, not just the 8086) is on a purely linear path by default, much like in other "primitive" languages like BASIC, and so there is nothing stopping the instruction pointer from "falling into" subroutines. Often this can be handy if you're trying to code a variation on a function whose only difference is doing a few extra things at the beginning, but it's something you'll need to guard against, either with a return to the operating system or an infinite loop. |
|||
<syntaxhighlight lang="asm">start: |
|||
mov al, 0x04 |
|||
mov bl, 0x05 |
|||
call multiply |
|||
;at this point in execution, the AX register contains 0x0900. |
|||
;more code goes here, ideally with some sort of guard against "fallthrough" into multiply. |
|||
; somewhere far away from start |
|||
multiply: |
|||
mul bl ;outputs 0x0014 to ax |
|||
ret</syntaxhighlight> |
|||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program functMul64.s */ |
/* program functMul64.s */ |
||
Line 189: | Line 206: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun multiply (a b) (* a b))</syntaxhighlight> |
||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">function multiply(a:Number, b:Number):Number { |
||
return a * b; |
return a * b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">function Multiply (A, B : Float) return Float;</syntaxhighlight> |
||
and an implementation of: |
and an implementation of: |
||
< |
<syntaxhighlight lang="ada">function Multiply (A, B : Float) return Float is |
||
begin |
begin |
||
return A * B; |
return A * B; |
||
end Multiply;</ |
end Multiply;</syntaxhighlight> |
||
The Ada 2012 standard provides an even simpler way to define and implement functions: |
The Ada 2012 standard provides an even simpler way to define and implement functions: |
||
< |
<syntaxhighlight lang="ada">function Multiply(A, B: Float) return Float is (A * B);</syntaxhighlight> |
||
Ada supports generic functions which can take generic formal parameters like the numeric type to use: |
Ada supports generic functions which can take generic formal parameters like the numeric type to use: |
||
< |
<syntaxhighlight lang="ada">generic |
||
type Number is digits <>; |
type Number is digits <>; |
||
function Multiply (A, B : Number) return Number;</ |
function Multiply (A, B : Number) return Number;</syntaxhighlight> |
||
implemented as: |
implemented as: |
||
< |
<syntaxhighlight lang="ada">function Multiply (A, B : Number) return Number is |
||
begin |
begin |
||
return A * B; |
return A * B; |
||
end Multiply;</ |
end Multiply;</syntaxhighlight> |
||
To use this, you need to instantiate the function for each type e.g. |
To use this, you need to instantiate the function for each type e.g. |
||
< |
<syntaxhighlight lang="ada"> |
||
with Multiply; |
with Multiply; |
||
... |
... |
||
Line 231: | Line 248: | ||
type My_Integer is Range -100..100; |
type My_Integer is Range -100..100; |
||
function Multiply_My_Integer is new Multiply(My_Integer); |
function Multiply_My_Integer is new Multiply(My_Integer); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">real |
||
multiply(real a, real b) |
multiply(real a, real b) |
||
{ |
{ |
||
return a * b; |
return a * b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 60}}== |
=={{header|ALGOL 60}}== |
||
Line 260: | Line 277: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">PROC multiply = ( LONG REAL a, b ) LONG REAL: |
||
( |
( |
||
a * b |
a * b |
||
)</ |
)</syntaxhighlight> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">long real procedure multiply( long real value a, b ); |
||
begin |
begin |
||
a * b |
a * b |
||
end</ |
end</syntaxhighlight> |
||
=={{header|ALGOL-M}}== |
=={{header|ALGOL-M}}== |
||
This implementation takes two integers and returns an integer. Note that a function is distinguished from a procedure, which does not return a value. |
This implementation takes two integers and returns an integer. Note that a function is distinguished from a procedure, which does not return a value. |
||
< |
<syntaxhighlight lang="algol">INTEGER FUNCTION MULTIPLY( A, B ); |
||
INTEGER A, B; |
INTEGER A, B; |
||
BEGIN |
BEGIN |
||
MULTIPLY := A * B; |
MULTIPLY := A * B; |
||
END;</ |
END;</syntaxhighlight> |
||
=={{header|Amazing Hopper}}== |
|||
Hopper has no functions, but they can be declared with macros, which are resolved at compile time. Access to the working stack is global, but "local" variables can be declared in program segments written after the ".locals" clause. Let's look at some examples of declaring "functions". |
|||
<syntaxhighlight lang="c"> |
|||
/* this need data into stack */ |
|||
#context Multiplication |
|||
mul |
|||
Return \\ |
|||
#synon Multiplication *getproduct |
|||
#context-free anothermul |
|||
/* #defn Args(*) #GENCODE $$$*$$$ #REVLIST=0,mov(#REVLIST);#ENDGEN, */ |
|||
Args 'a,b' |
|||
Return ( #(a*b) )\\ |
|||
#synon anothermul *getanotherproduct |
|||
#include <jambo.h> |
|||
#prototype _multiply(_X_,_Y_) |
|||
#synon __multiply Multiply |
|||
Main |
|||
/* "prototipos" of functions and procedures. |
|||
Solves internaly */ |
|||
Printnl ( Multiply ( 10, 4 ) ) |
|||
Printnl ( __multiply ( 10, 4 ) ) |
|||
/* definición alternativa 1 */ |
|||
Printnl ( Set' 10,4 ', Gosub ' Multiply2 ') |
|||
/* aseembler Hopper 1 */ |
|||
{10,4} jsub( Multiply3 ), {"\n"} print |
|||
/* assembler Hopper 2 */ |
|||
{10,4} jsub( Multiply4 ), {"\n"} print |
|||
/* context */ |
|||
Set '10,4', now get product, and print with newline |
|||
/* context-free */ |
|||
Set '10,4', and get another product; then print with newline |
|||
End |
|||
.locals /* Subrutines */ |
|||
_multiply(a,b) |
|||
Return ( Mul(a,b) ) |
|||
/* Define is macro. Others macros: Function, Procedure: |
|||
#defn Define(_F_,*) _F_:,#GENCODE $$$*$$$ #REVLIST=0;mov(#REVLIST);#ENDGEN; |
|||
#defn Function(_F_,*) _F_:,#GENCODE $$$*$$$ #REVLIST=0;mov(#REVLIST);#ENDGEN; |
|||
#defn Procedure(_F_,*) _F_:,#GENCODE $$$*$$$ #REVLIST=0;mov(#REVLIST);#ENDGEN; |
|||
*/ |
|||
Define 'Multiply2, a,b' |
|||
Return ( Mul(a,b) ) |
|||
Multiply3: |
|||
b=0, mov(b), a=0, mov(a) |
|||
{a,b}mul /* result into stack */ |
|||
Return |
|||
Multiply4: |
|||
mul /* get values from stack, |
|||
and put result into stack */ |
|||
back /* Return */ |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
40.000000 |
|||
40.000000 |
|||
40.000000 |
|||
40.000000 |
|||
40.000000 |
|||
40.000000 |
|||
40.000000 |
|||
</pre> |
|||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
< |
<syntaxhighlight lang="amigae">PROC my_molt(a,b) |
||
-> other statements if needed... here they are not |
-> other statements if needed... here they are not |
||
ENDPROC a*b -> return value |
ENDPROC a*b -> return value |
||
Line 290: | Line 384: | ||
PROC main() |
PROC main() |
||
WriteF('\d\n', my_molt(10,20)) |
WriteF('\d\n', my_molt(10,20)) |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|AntLang}}== |
=={{header|AntLang}}== |
||
< |
<syntaxhighlight lang="antlang">multiply: * /`*' is a normal function |
||
multiply: {x * y}</ |
multiply: {x * y}</syntaxhighlight> |
||
Explicit definition has the syntax: |
Explicit definition has the syntax: |
||
< |
<syntaxhighlight lang="antlang">{expr-or-def1; expr-or-def2; ..; return-expr}</syntaxhighlight> |
||
Inside functions, the variable args contains the sequence of arguments. |
Inside functions, the variable args contains the sequence of arguments. |
||
x, y and z contain the first, second and third argument. |
x, y and z contain the first, second and third argument. |
||
Line 302: | Line 396: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
{{works with|GNU_APL}} |
{{works with|GNU_APL}} |
||
< |
<syntaxhighlight lang="apl"> |
||
⍝⍝ APL2 'tradfn' (traditional function) |
⍝⍝ APL2 'tradfn' (traditional function) |
||
⍝⍝ This syntax works in all dialects including GNU APL and Dyalog. |
⍝⍝ This syntax works in all dialects including GNU APL and Dyalog. |
||
Line 311: | Line 405: | ||
⍝⍝ A 'dfn' or 'lambda' (anonymous function) |
⍝⍝ A 'dfn' or 'lambda' (anonymous function) |
||
multiply ← {⍺×⍵} |
multiply ← {⍺×⍵} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{works with|Dyalog_APL}} |
{{works with|Dyalog_APL}} |
||
< |
<syntaxhighlight lang="apl"> |
||
⍝⍝ Dyalog dfn (lambda) syntax |
⍝⍝ Dyalog dfn (lambda) syntax |
||
multiply ← × |
multiply ← × |
||
</syntaxhighlight> |
|||
</lang> |
|||
Works on arrays of any rank (any number of dimensions): atoms, lists, tables, etc. |
Works on arrays of any rank (any number of dimensions): atoms, lists, tables, etc. |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">to multiply(a as number, b as number) |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
A function in AppleScript is called a "handler". It can take one of three different forms, depending on what the scripter finds most convenient. Calls to it must match the form used in the handler definition |
A function in AppleScript is called a "handler". It can take one of three different forms, depending on what the scripter finds most convenient. Calls to it must match the form used in the handler definition. Either <code>to</code> or <code>on</code> may be used as the first word in the handler definition. When the script is compiled, the handler label is automatically appended to the <code>end</code> line too if it wasn't written in. |
||
Handler names followed by zero or more parameters within parentheses are called "positional" -- the number and order of the parameters in the caller must match those in the handler definition. |
|||
<lang applescript>on multiply(a, b) |
|||
<syntaxhighlight lang="applescript">on multiply(a, b) |
|||
return a * b |
return a * b |
||
end multiply |
end multiply |
||
multiply(2, 3)</ |
multiply(2, 3)</syntaxhighlight> |
||
AppleScript also offers handlers with " |
AppleScript also offers handlers with "prepositional" labeled parameters. These aren't used often because the set of AppleScript-defined prepositions makes it difficult to choose ones that make sense in English. |
||
These prepositions can be used: <code>about, above, against, apart from, around, aside from, at, below, beneath, beside, between, by, for, from, instead of, into, on, onto, out of, over, since, thru, through, and under</code>. Also, <code>of</code> is available, but if used it must be the first parameter. |
|||
<lang applescript>on multiplication of a by b |
|||
Example: |
|||
<syntaxhighlight lang="applescript">on multiplication of a by b |
|||
return a * b |
return a * b |
||
end multiplication |
end multiplication |
||
multiplication of 2 by 3 -- Or: (multiplication by 3) of 2, or: 2's (multiplication by 3)</ |
multiplication of 2 by 3 -- Or: (multiplication by 3) of 2, or: 2's (multiplication by 3)</syntaxhighlight> |
||
Labeled parameters don't need to be in the same order in the calls as in the handler definition, but <code>of</code>, if used, is regarded as a direct parameter and requires some parenthesis if it's not given first or if the context isn't entirely clear. |
Labeled parameters don't need to be in the same order in the calls as in the handler definition, but <code>of</code>, if used, is regarded as a direct parameter and requires some parenthesis if it's not given first or if the context isn't entirely clear. |
||
Line 345: | Line 445: | ||
For the past few years, handlers with "interleaved" parameters have also been possible. They're a development from AppleScriptObjectiveC and coders can specify their own labels provided these aren't reserved words. Calls to these handlers must reference the handlers' "owners", which are usually represented within the same script by the keyword <code>my</code>. The parameter order is the same in the calls as in the handler definitions: |
For the past few years, handlers with "interleaved" parameters have also been possible. They're a development from AppleScriptObjectiveC and coders can specify their own labels provided these aren't reserved words. Calls to these handlers must reference the handlers' "owners", which are usually represented within the same script by the keyword <code>my</code>. The parameter order is the same in the calls as in the handler definitions: |
||
< |
<syntaxhighlight lang="applescript">on multiply:a |by|:b -- 'by' is "barred" here because otherwise it's a reserved word. |
||
return a * b |
return a * b |
||
end multiply:|by|: |
end multiply:|by|: |
||
my multiply:2 |by|:3</ |
my multiply:2 |by|:3</syntaxhighlight> |
||
=={{header|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> |
|||
=={{header|Argile}}== |
=={{header|Argile}}== |
||
< |
<syntaxhighlight lang="argile">use std |
||
.: multiply <real a, real b> :. -> real {a * b}</ |
.: multiply <real a, real b> :. -> real {a * b}</syntaxhighlight> |
||
with a macro and a variable number of parameters: |
with a macro and a variable number of parameters: |
||
< |
<syntaxhighlight lang="argile">use std |
||
=: multiply <real a> [<real b>...] := -> real {Cgen a (@@1 (Cgen " * " b))}</ |
=: multiply <real a> [<real b>...] := -> real {Cgen a (@@1 (Cgen " * " b))}</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program functMul.s */ |
/* program functMul.s */ |
||
Line 508: | Line 598: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ArnoldC}}== |
=={{header|ArnoldC}}== |
||
< |
<syntaxhighlight lang="arnoldc">LISTEN TO ME VERY CAREFULLY multiply |
||
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a |
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a |
||
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b |
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b |
||
Line 522: | Line 612: | ||
ENOUGH TALK |
ENOUGH TALK |
||
I'LL BE BACK product |
I'LL BE BACK product |
||
HASTA LA VISTA, BABY</ |
HASTA LA VISTA, BABY</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="arturo">multiply: $[x,y][x*y] |
||
print multiply 3 7 |
print multiply 3 7 |
||
Line 534: | Line 624: | ||
print multiply2 3 7 |
print multiply2 3 7 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 542: | Line 632: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">MsgBox % multiply(10,2) |
||
multiply(multiplicand, multiplier) { |
multiply(multiplicand, multiplier) { |
||
Return (multiplicand * multiplier) |
Return (multiplicand * multiplier) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
< |
<syntaxhighlight lang="autoit">#AutoIt Version: 3.2.10.0 |
||
$I=11 |
$I=11 |
||
$J=12 |
$J=12 |
||
Line 555: | Line 645: | ||
Func product($a,$b) |
Func product($a,$b) |
||
Return $a * $b |
Return $a * $b |
||
EndFunc</ |
EndFunc</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">function multiply(a, b) |
||
{ |
{ |
||
return a*b |
return a*b |
||
Line 564: | Line 654: | ||
BEGIN { |
BEGIN { |
||
print multiply(5, 6) |
print multiply(5, 6) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
< |
<syntaxhighlight lang="axe">Lbl MULT |
||
r₁*r₂ |
r₁*r₂ |
||
Return</ |
Return</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|ANSI BASIC}}=== |
|||
{{works with|QBasic}} |
|||
In ANSI BASIC, functions can be defined as either formulas or multi-line external or internal subroutines. External functions are independent program units that can be called from within the program. Internal functions are considered part of the program unit they are contained in and can only be called from within that unit. External functions do not share any information with other program units and exchange information through parameters and returned values. Internal functions share everything with their surrounding program unit except for their parameters. Internal functions do not have local variables. |
|||
<lang qbasic>DECLARE FUNCTION multiply% (a AS INTEGER, b AS INTEGER) |
|||
{{works with|Decimal BASIC}} |
|||
<syntaxhighlight lang="basic"> |
|||
100 DEF Multiply(A, B) = A * B |
|||
110 DECLARE FUNCTION MultiplyI |
|||
120 DECLARE EXTERNAL FUNCTION MultiplyE |
|||
130 PRINT Multiply(3, 1.23456) |
|||
140 PRINT MultiplyI(3, 1.23456) |
|||
150 PRINT MultiplyE(3, 1.23456) |
|||
160 FUNCTION MultiplyI(X, Y) |
|||
170 LET MultiplyI = X * Y |
|||
180 END FUNCTION |
|||
190 END |
|||
200 EXTERNAL FUNCTION MultiplyE(A, B) |
|||
210 LET MultiplyE = A * B |
|||
220 END FUNCTION |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
3.70368 |
|||
3.70368 |
|||
3.70368 |
|||
</pre> |
|||
==={{header|Applesoft BASIC}}=== |
|||
FUNCTION multiply% (a AS INTEGER, b AS INTEGER) |
|||
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. |
|||
multiply = a * b |
|||
END FUNCTION</lang> |
|||
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. |
|||
<syntaxhighlight lang="basic">10 DEF FN MULTIPLY(P) = P(P) * P(P+1) |
|||
20 P(1) = 611 : P(2) = 78 : PRINT FN MULTIPLY(1)</syntaxhighlight> |
|||
<syntaxhighlight lang="basic">47658</syntaxhighlight> |
|||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
< |
<syntaxhighlight lang="freebasic">function multiply(a, b) |
||
return a * b |
return a * b |
||
end function</ |
end function</syntaxhighlight> |
||
==={{header|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: |
|||
<syntaxhighlight lang="bbcbasic">PRINT FNmultiply(6,7) |
|||
END |
|||
DEF FNmultiply(a,b) = a * b</syntaxhighlight> |
|||
Multiline function: |
|||
<syntaxhighlight lang="bbcbasic">DEF FNmultiply(a,b) |
|||
LOCAL c |
|||
c = a * b |
|||
= c</syntaxhighlight> |
|||
=== {{header|Chipmunk Basic}} === |
|||
<syntaxhighlight lang="basic"> |
|||
10 rem Function definition |
|||
20 rem ** 1. Function defined as formula. An obsolete way - does not work properly with integer formal parameters (e.g. x%). |
|||
30 def fnmultiply(a, b) = a * b |
|||
40 rem ** Call the functions |
|||
50 print multiply(3,1.23456) |
|||
60 print fn multiply(3,1.23456) |
|||
70 end |
|||
200 rem ** 2. Function defined as subroutine returning a value |
|||
210 sub multiply(a,b) |
|||
220 multiply = a*b |
|||
230 end sub |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
3.70368 |
|||
3.70368 |
|||
</pre> |
|||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
In Commodore BASIC function definition can consist of any mathematical operation other functions or commands which result in a numeric expression. The definition is limited to single statement, and it accepts only a single argument. When using the function, keyword fn must precede the function name, which itself must be uniquely distinguishable by its first two characters. |
In Commodore BASIC function definition can consist of any mathematical operation other functions or commands which result in a numeric expression. The definition is limited to single statement, and it accepts only a single argument. When using the function, keyword fn must precede the function name, which itself must be uniquely distinguishable by its first two characters. |
||
< |
<syntaxhighlight lang="basic">10 DEF FN MULT(X) = X*Y |
||
20 Y = 4 : REM VALUE OF SECOND ARGUMENT MUST BE ASSIGNED SEPARATELY |
20 Y = 4 : REM VALUE OF SECOND ARGUMENT MUST BE ASSIGNED SEPARATELY |
||
30 PRINT FN MULT(3)</ |
30 PRINT FN MULT(3)</syntaxhighlight> |
||
==={{header| |
==={{header|Creative Basic}}=== |
||
<syntaxhighlight lang="creative basic"> |
|||
<lang IS-BASIC>100 DEF MULTIPLY(A,B)=A*B</lang> |
|||
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. |
|||
</syntaxhighlight> |
|||
==={{header|FreeBASIC}}=== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Function multiply(d1 As Double, d2 As Double) As Double |
|||
Return d1 * d2 |
|||
End Function</syntaxhighlight> |
|||
This function could either be used for all numeric types (as they are implicitly convertible to Double) |
|||
or could be overloaded to deal with each such type (there are 12 of them). |
|||
Alternatively, one could write a macro though this wouldn't be type-safe: |
|||
<syntaxhighlight lang="freebasic">#Define multiply(d1, d2) (d1) * (d2)</syntaxhighlight> |
|||
==={{header|FutureBasic}}=== |
|||
<syntaxhighlight lang="futurebasic">window 1 |
|||
local fn multiply( a as long, b as long ) as long |
|||
end fn = a * b |
|||
print fn multiply( 3, 9 ) |
|||
HandleEvents</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
27 |
|||
</pre> |
|||
==={{header|Gambas}}=== |
|||
'''[https://gambas-playground.proko.eu/?gist=bc93236474d9937217dd4117026f7441 Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Print Multiply(56, 4.66) |
|||
End |
|||
Public Sub Multiply(f1 As Float, f2 As Float) As Float |
|||
Return f1 * f2 |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
260.96 |
|||
</pre> |
|||
==={{header| |
==={{header|GW-BASIC}}=== |
||
{{works with|BASICA}} |
{{works with|BASICA}} |
||
< |
<syntaxhighlight lang="basic">10 DEF FNMULT(X,Y)=X*Y |
||
20 PRINT FNMULT(5,6) |
20 PRINT FNMULT(5,6) |
||
39 END |
39 END |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 DEF MULTIPLY(A,B)=A*B</syntaxhighlight> |
|||
==={{header|IWBASIC}}=== |
|||
<syntaxhighlight 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) |
|||
PRINT |
|||
'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) |
|||
PRINT |
|||
'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)) |
|||
PRINT |
|||
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 |
|||
</syntaxhighlight> |
|||
==={{header|Liberty BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
<syntaxhighlight lang="lb">' define & call a function |
|||
print multiply( 3, 1.23456) |
|||
wait |
|||
function multiply( m1, m2) |
|||
multiply =m1 *m2 |
|||
end function |
|||
end</syntaxhighlight> |
|||
==={{header|Locomotive Basic}}=== |
|||
<syntaxhighlight lang="locobasic">10 DEF FNmultiply(x,y)=x*y |
|||
20 PRINT FNmultiply(2,PI)</syntaxhighlight> |
|||
Function names are always preceded by "FN" in Locomotive BASIC. Also, PI is predefined by the interpreter as 3.14159265. |
|||
==={{header|OxygenBasic}}=== |
==={{header|OxygenBasic}}=== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
'SHORT FORMS: |
'SHORT FORMS: |
||
float multiply(float a,b) = a * b |
float multiply(float a,b) = a * b |
||
Line 618: | Line 968: | ||
'TEST: |
'TEST: |
||
print multiply(pi,2) '6.28... |
print multiply(pi,2) '6.28... |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|PureBasic}}=== |
|||
<syntaxhighlight lang="purebasic">Procedure multiply(a,b) |
|||
ProcedureReturn a*b |
|||
EndProcedure</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
< |
<syntaxhighlight lang="qbasic">'This function could either be used for all numeric types |
||
'(as they are implicitly convertible to Double) |
'(as they are implicitly convertible to Double) |
||
FUNCTION multiply# (a AS DOUBLE, b AS DOUBLE) |
FUNCTION multiply# (a AS DOUBLE, b AS DOUBLE) |
||
Line 632: | Line 987: | ||
PRINT multiply(3, 1.23456) |
PRINT multiply(3, 1.23456) |
||
PRINT FNmultiply#(3, 1.23456)</ |
PRINT FNmultiply#(3, 1.23456)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 3.703680038452148</pre> |
<pre> 3.703680038452148</pre> |
||
==={{header|QuickBASIC}}=== |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic">DECLARE FUNCTION multiply% (a AS INTEGER, b AS INTEGER) |
|||
FUNCTION multiply% (a AS INTEGER, b AS INTEGER) |
|||
multiply = a * b |
|||
END FUNCTION</syntaxhighlight> |
|||
==={{header|REALbasic}}=== |
|||
<syntaxhighlight lang="vb"> |
|||
Function Multiply(a As Integer, b As Integer) As Integer |
|||
Return a * b |
|||
End Function |
|||
</syntaxhighlight> |
|||
==={{header|S-BASIC}}=== |
|||
S-BASIC is unusual in that the function return value is assigned to the END statement that terminates the function. |
|||
<syntaxhighlight lang="basic"> |
|||
function multiply(a, b = integer) = integer |
|||
end = a * b |
|||
rem - exercise the function |
|||
print "The product of 9 times 3 is"; multiply(9, 3) |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
The product of 9 times 3 is 27 |
|||
</pre> |
|||
==={{header|SmallBASIC}}=== |
|||
<syntaxhighlight lang="qbasic"> |
|||
func multiply(a, b) |
|||
return a * b |
|||
end |
|||
print "2 * 3 = "; multiply(2, 3) |
|||
</syntaxhighlight> |
|||
If function definition is only one line, <code>def</code> can be used: |
|||
<syntaxhighlight lang="qbasic"> |
|||
def multiply(a, b) = a * b |
|||
print "2 * 3 = "; multiply(2, 3) |
|||
</syntaxhighlight> |
|||
==={{header|True BASIC}}=== |
==={{header|True BASIC}}=== |
||
The <code>FUNCTION</code> and <code>DEF</code> commands are synonymous and can be interchanged. |
The <code>FUNCTION</code> and <code>DEF</code> commands are synonymous and can be interchanged. |
||
< |
<syntaxhighlight lang="qbasic">FUNCTION multiply(a, b) |
||
LET multiply = a * b |
LET multiply = a * b |
||
END FUNCTION |
END FUNCTION |
||
Line 646: | Line 1,049: | ||
DEF multiply (a, b) = a * b |
DEF multiply (a, b) = a * b |
||
END</ |
END</syntaxhighlight> |
||
==={{header|TI-89 BASIC}}=== |
|||
<syntaxhighlight lang="ti89b">multiply(a, b) |
|||
Func |
|||
Return a * b |
|||
EndFunc</syntaxhighlight> |
|||
==={{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. |
|||
<syntaxhighlight lang="text">Print FUNC(_multiply (23, 65)) |
|||
End |
|||
_multiply Param (2) : Return (a@ * b@)</syntaxhighlight> |
|||
==={{header|VBA}}=== |
|||
<syntaxhighlight lang="vb">Function Multiply(lngMcand As Long, lngMplier As Long) As Long |
|||
Multiply = lngMcand * lngMplier |
|||
End Function</syntaxhighlight> |
|||
To use this function : |
|||
<syntaxhighlight lang="vb">Sub Main() |
|||
Dim Result As Long |
|||
Result = Multiply(564231, 897) |
|||
End Sub</syntaxhighlight> |
|||
==={{header|VBScript}}=== |
|||
<syntaxhighlight lang="vb">function multiply( multiplicand, multiplier ) |
|||
multiply = multiplicand * multiplier |
|||
end function</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="vb">dim twosquared |
|||
twosquared = multiply(2, 2)</syntaxhighlight> |
|||
==={{header|Visual Basic}}=== |
|||
{{works with|Visual Basic|VB6 Standard}} |
|||
<syntaxhighlight lang="vb"> |
|||
Function multiply(a As Integer, b As Integer) As Integer |
|||
multiply = a * b |
|||
End Function |
|||
</syntaxhighlight> |
|||
Call the function |
|||
<syntaxhighlight lang="vb">Multiply(6, 111)</syntaxhighlight> |
|||
==={{header|Visual Basic .NET}}=== |
|||
<syntaxhighlight lang="vbnet">Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer |
|||
Return a * b |
|||
End Function</syntaxhighlight> |
|||
Call the function |
|||
<syntaxhighlight lang="vbnet">Multiply(1, 1)</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
< |
<syntaxhighlight lang="yabasic">sub multiply(a, b) |
||
return a * b |
return a * b |
||
end sub</ |
end sub</syntaxhighlight> |
||
==={{header|Xojo}}=== |
|||
<syntaxhighlight lang="vbnet">Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer |
|||
Return a * b |
|||
End Function</syntaxhighlight> |
|||
Call the function |
|||
<syntaxhighlight lang="vbnet">Dim I As Integer = Multiply(7, 6)</syntaxhighlight> |
|||
==={{header|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 |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Windows batch files only have procedures, not functions. Instead, environmental variables can be used as a global shared state. |
Windows batch files only have procedures, not functions. Instead, environmental variables can be used as a global shared state. |
||
<lang>@ECHO OFF |
<syntaxhighlight lang="text">@ECHO OFF |
||
SET /A result = 0 |
SET /A result = 0 |
||
CALL :multiply 2 3 |
CALL :multiply 2 3 |
||
Line 665: | Line 1,129: | ||
GOTO :eof |
GOTO :eof |
||
:eof</ |
:eof</syntaxhighlight> |
||
=={{header|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> |
|||
=={{header|bc}}== |
=={{header|bc}}== |
||
{{Works with|GNU bc}} |
{{Works with|GNU bc}} |
||
< |
<syntaxhighlight lang="bc">define multiply(a, b) { return a*b } |
||
print multiply(2, 3)</ |
print multiply(2, 3)</syntaxhighlight> |
||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
A function is simply defined as an expression in terms of its arguments. |
A function is simply defined as an expression in terms of its arguments. |
||
< |
<syntaxhighlight lang="bcpl">let multiply(a, b) = a * b</syntaxhighlight> |
||
Defining a block of code that executes some statements and then returns a |
Defining a block of code that executes some statements and then returns a |
||
Line 696: | Line 1,146: | ||
to define a function containing imperative statements. When used this way, |
to define a function containing imperative statements. When used this way, |
||
it is equivalent to the functions in most other imperative languages. |
it is equivalent to the functions in most other imperative languages. |
||
< |
<syntaxhighlight lang="bcpl">let multiply(a, b) = valof |
||
$( // any imperative statements could go here |
$( // any imperative statements could go here |
||
resultis a * b |
resultis a * b |
||
$)</ |
$)</syntaxhighlight> |
||
=={{header|BlitzMax}}== |
|||
<syntaxhighlight lang="blitzmax">function multiply:float( a:float, b:float ) |
|||
return a*b |
|||
end function |
|||
print multiply(3.1416, 1.6180)</syntaxhighlight> |
|||
{{out}}<pre>5.08310890</pre> |
|||
=={{header|Boo}}== |
=={{header|Boo}}== |
||
< |
<syntaxhighlight lang="boo">def multiply(x as int, y as int): |
||
return x * y |
return x * y |
||
print multiply(3, 2)</ |
print multiply(3, 2)</syntaxhighlight> |
||
=={{header|Binary Lambda Calculus}}== |
|||
In lambda calculus, multiplication on Church numerals is <code>mul = \m \n \f. m (n f)</code> which in BLC is |
|||
<pre>00 00 00 01 1110 01 110 10</pre> |
|||
If mul is used several times within an expression E, then they can share the same definition by using <code>(\mul. E)(\m\n\f. m (n f))</code>. For example, the cube function is <code>\n. (\mul. mul n (mul n n)) (\m\n\f. m (n f))</code> which in BLC is |
|||
<pre>00 01 00 01 01 10 110 01 01 10 110 110 0000000111100111010</pre> |
|||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Tacit definition: |
Tacit definition: |
||
<lang |
<syntaxhighlight lang="bqn">Multiply ← ×</syntaxhighlight> |
||
With names: |
With names: |
||
<lang |
<syntaxhighlight lang="bqn">Multiply ← {𝕨×𝕩}</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">multiply=a b.!arg:(?a.?b)&!a*!b; |
||
out$multiply$(123456789.987654321); { writes 121932631112635269 to standard output }</ |
out$multiply$(123456789.987654321); { writes 121932631112635269 to standard output }</syntaxhighlight> |
||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">multiply = { x, y | x * y } |
||
p multiply 3 14 #Prints 42</ |
p multiply 3 14 #Prints 42</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">double multiply(double a, double b) |
||
{ |
{ |
||
return a * b; |
return a * b; |
||
}</ |
}</syntaxhighlight> |
||
===Macros=== |
===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). |
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). |
||
< |
<syntaxhighlight lang="c">#define MULTIPLY(X, Y) ((X) * (Y))</syntaxhighlight> |
||
Parentheses should be added around parameters in the function definition to avoid order of operations errors when someone uses the macro as such: |
Parentheses should be added around parameters in the function definition to avoid order of operations errors when someone uses the macro as such: |
||
< |
<syntaxhighlight lang="c">x = MULTIPLY(x + z, y);</syntaxhighlight> |
||
A program with that call would be compiled as if this were coded instead: |
A program with that call would be compiled as if this were coded instead: |
||
< |
<syntaxhighlight lang="c">x = ((x + z) * (y));</syntaxhighlight> |
||
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 sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">static double multiply(double a, double b) |
||
{ |
{ |
||
return a * b; |
return a * b; |
||
}</ |
}</syntaxhighlight> |
||
Anonymous function: |
Anonymous function: |
||
< |
<syntaxhighlight lang="csharp">Func<double, double, double> multiply = ((a,b) => a*b);</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 749: | Line 1,218: | ||
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: |
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: |
||
< |
<syntaxhighlight lang="cpp">inline double multiply(double a, double b) |
||
{ |
{ |
||
return a*b; |
return a*b; |
||
}</ |
}</syntaxhighlight> |
||
If not only doubles, but numbers of arbitrary types are to be multiplied, a function template can be used: |
If not only doubles, but numbers of arbitrary types are to be multiplied, a function template can be used: |
||
< |
<syntaxhighlight lang="cpp">template<typename Number> |
||
Number multiply(Number a, Number b) |
Number multiply(Number a, Number b) |
||
{ |
{ |
||
return a*b; |
return a*b; |
||
}</ |
}</syntaxhighlight> |
||
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. |
||
Since C++20, the template parameters can be inferred using <tt>auto</tt>: |
Since C++20, the template parameters can be inferred using <tt>auto</tt>: |
||
< |
<syntaxhighlight lang="cpp">auto multiply(auto a, auto b) |
||
{ |
{ |
||
return a*b; |
return a*b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Chapel}}== |
|||
<syntaxhighlight lang="text"> |
|||
proc multiply(a, b) |
|||
{ |
|||
return a * b; |
|||
} |
|||
</syntaxhighlight> |
|||
Can require that the two arguments be of the same type. |
|||
<syntaxhighlight lang="text"> |
|||
proc multiply(a : ?t ... 2) |
|||
{ |
|||
return a(0) * a(1) |
|||
} |
|||
</syntaxhighlight> |
|||
Will work on any type where the * operator is defined. |
|||
=={{header|ChucK}}== |
=={{header|ChucK}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
fun float multiply (float a, float b) |
fun float multiply (float a, float b) |
||
{ |
{ |
||
Line 775: | Line 1,263: | ||
// uncomment next line and change values to test |
// uncomment next line and change values to test |
||
//<<< multiply(16,4) >>>; |
//<<< multiply(16,4) >>>; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clay}}== |
=={{header|Clay}}== |
||
< |
<syntaxhighlight lang="clay">multiply(x,y) = x * y;</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(defn multiply [x y] |
||
(* x y)) |
(* x y)) |
||
(multiply 4 5)</ |
(multiply 4 5)</syntaxhighlight> |
||
Or with multiple arities (in the manner of the actual <tt>*</tt> function): |
Or with multiple arities (in the manner of the actual <tt>*</tt> function): |
||
< |
<syntaxhighlight lang="lisp">(defn multiply |
||
([] 1) |
([] 1) |
||
([x] x) |
([x] x) |
||
Line 793: | Line 1,281: | ||
(reduce * (* x y) more))) |
(reduce * (* x y) more))) |
||
(multiply 2 3 4 5) ; 120</ |
(multiply 2 3 4 5) ; 120</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
The following is a function that multiplies two integers and ignores any error conditions |
The following is a function that multiplies two integers and ignores any error conditions |
||
(as most examples do). |
(as most examples do). |
||
< |
<syntaxhighlight lang="clu">multiply = proc (a, b: int) returns (int) |
||
return(a * b) |
return(a * b) |
||
end multiply</ |
end multiply</syntaxhighlight> |
||
The following is a type-parameterized function that wraps the built-in multiplication operator |
The following is a type-parameterized function that wraps the built-in multiplication operator |
||
Line 806: | Line 1,294: | ||
It also shows the complete syntax of a function definition (type parameterization, |
It also shows the complete syntax of a function definition (type parameterization, |
||
signals, and a <code>where</code> clause). |
signals, and a <code>where</code> clause). |
||
< |
<syntaxhighlight lang="clu">multiply = proc [T: type] (a, b: T) returns (T) |
||
signals (overflow, underflow) |
signals (overflow, underflow) |
||
where T has mul: proctype (T, T) returns (T) |
where T has mul: proctype (T, T) returns (T) |
||
signals (overflow, underflow) |
signals (overflow, underflow) |
||
return(a * b) resignal overflow, underflow |
return(a * b) resignal overflow, underflow |
||
end multiply</ |
end multiply</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
In COBOL, ''multiply'' is a reserved word, so the requirements must be relaxed to allow a different function name. |
In COBOL, ''multiply'' is a reserved word, so the requirements must be relaxed to allow a different function name. |
||
{{ |
{{Works with|COBOL-85}} |
||
The following uses a subprogram: |
|||
<lang COBOL> IDENTIFICATION DIVISION. |
|||
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. myTest. |
PROGRAM-ID. myTest. |
||
DATA DIVISION. |
DATA DIVISION. |
||
WORKING-STORAGE SECTION. |
WORKING-STORAGE SECTION. |
||
01 x |
01 x PICTURE IS 9(3) VALUE IS 3. |
||
01 y |
01 y PICTURE IS 9(3) VALUE IS 2. |
||
01 z |
01 z PICTURE IS 9(9). |
||
PROCEDURE DIVISION. |
PROCEDURE DIVISION. |
||
CALL "myMultiply" USING |
CALL "myMultiply" USING |
||
Line 835: | Line 1,324: | ||
DATA DIVISION. |
DATA DIVISION. |
||
LINKAGE SECTION. |
LINKAGE SECTION. |
||
01 x |
01 x PICTURE IS 9(3). |
||
01 y |
01 y PICTURE IS 9(3). |
||
01 z |
01 z PICTURE IS 9(9). |
||
PROCEDURE DIVISION USING x, y, z. |
PROCEDURE DIVISION USING BY REFERENCE x, y, z. |
||
MULTIPLY x BY y GIVING z. |
MULTIPLY x BY y GIVING z. |
||
EXIT PROGRAM. |
EXIT PROGRAM. |
||
END PROGRAM myMultiply.</ |
END PROGRAM myMultiply.</syntaxhighlight> |
||
{{Works with|COBOL 2002}} |
|||
This example uses user-defined functions, which were added in COBOL 2002. |
|||
This example uses user-defined functions. |
|||
{{works with|GNU Cobol|2.0}} |
|||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. myTest. |
PROGRAM-ID. myTest. |
||
ENVIRONMENT DIVISION. |
ENVIRONMENT DIVISION. |
||
Line 853: | Line 1,342: | ||
DATA DIVISION. |
DATA DIVISION. |
||
WORKING-STORAGE SECTION. |
WORKING-STORAGE SECTION. |
||
01 x |
01 x PICTURE IS 9(3) VALUE IS 3. |
||
01 y |
01 y PICTURE IS 9(3) VALUE IS 2. |
||
PROCEDURE DIVISION. |
PROCEDURE DIVISION. |
||
DISPLAY myMultiply(x, y). |
DISPLAY myMultiply(x, y). |
||
Line 864: | Line 1,353: | ||
DATA DIVISION. |
DATA DIVISION. |
||
LINKAGE SECTION. |
LINKAGE SECTION. |
||
01 x |
01 x PICTURE IS 9(3). |
||
01 y |
01 y PICTURE IS 9(3). |
||
01 z |
01 z PICTURE IS 9(9). |
||
PROCEDURE DIVISION USING x, y RETURNING z. |
PROCEDURE DIVISION USING x, y RETURNING z. |
||
MULTIPLY x BY y GIVING z. |
MULTIPLY x BY y GIVING z. |
||
GOBACK. |
|||
END FUNCTION myMultiply.</ |
END FUNCTION myMultiply.</syntaxhighlight> |
||
=={{header|Coco}}== |
=={{header|Coco}}== |
||
Line 876: | Line 1,365: | ||
As CoffeeScript. In addition, Coco provides some syntactic sugar for accessing the <code>arguments</code> array reminiscent of Perl's <code>@_</code>: |
As CoffeeScript. In addition, Coco provides some syntactic sugar for accessing the <code>arguments</code> array reminiscent of Perl's <code>@_</code>: |
||
< |
<syntaxhighlight lang="coco">multiply = -> @@0 * @@1</syntaxhighlight> |
||
Furthermore, when no parameter list is defined, the first argument is available as <code>it</code>: |
Furthermore, when no parameter list is defined, the first argument is available as <code>it</code>: |
||
< |
<syntaxhighlight lang="coco">double = -> 2 * it</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript">multiply = (a, b) -> a * b</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
====Tag style==== |
|||
<lang coldfusion><cffunction name="multiply" returntype="numeric"> |
|||
<syntaxhighlight lang="coldfusion"><cffunction name="multiply" returntype="numeric"> |
|||
<cfargument name="a" type="numeric"> |
<cfargument name="a" type="numeric"> |
||
<cfargument name="b" type="numeric"> |
<cfargument name="b" type="numeric"> |
||
<cfreturn a * b> |
<cfreturn a * b> |
||
</cffunction></ |
</cffunction></syntaxhighlight> |
||
====Script style==== |
|||
<syntaxhighlight lang="lisp">numeric function multiply(required numeric a, required numeric b){ |
|||
return a * b; |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 896: | Line 1,393: | ||
===Ordinary 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. |
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. |
||
< |
<syntaxhighlight lang="lisp">(defun multiply (a b) |
||
(* a b)) |
(* a b)) |
||
(multiply 2 3)</ |
(multiply 2 3)</syntaxhighlight> |
||
====User-Defined Compiler Optimization of Functions==== |
====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: |
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: |
||
< |
<syntaxhighlight lang="lisp">(define-compiler-macro multiply (&whole expr a b) |
||
(if (and (constantp a) (constantp b)) |
(if (and (constantp a) (constantp b)) |
||
(* (eval a) (eval b)) |
(* (eval a) (eval b)) |
||
expr)) ;; no macro recursion if we just return expr; the job is done! </ |
expr)) ;; no macro recursion if we just return expr; the job is done! </syntaxhighlight> |
||
Lisp implementations do not have to honor compiler macros. Usually compilers make use of them, but evaluators do not. |
Lisp implementations do not have to honor compiler macros. Usually compilers make use of them, but evaluators do not. |
||
Line 938: | Line 1,435: | ||
Also, the DEFGENERIC is optional, since the first DEFMETHOD will define the generic function, but good practice. |
Also, the DEFGENERIC is optional, since the first DEFMETHOD will define the generic function, but good practice. |
||
< |
<syntaxhighlight lang="lisp"> |
||
;;; terrific example coming |
;;; terrific example coming |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Cowgol}}== |
=={{header|Cowgol}}== |
||
< |
<syntaxhighlight lang="cowgol">sub multiply(a: int32, b: int32): (rslt: int32) is |
||
rslt := a * b; |
rslt := a * b; |
||
end sub</ |
end sub</syntaxhighlight> |
||
=={{header|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> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">// A function: |
||
int multiply1(int a, int b) { |
int multiply1(int a, int b) { |
||
return a * b; |
return a * b; |
||
Line 1,002: | Line 1,468: | ||
import std.stdio; |
import std.stdio; |
||
writeln("2 * 3 = ", result); |
writeln("2 * 3 = ", result); |
||
}</ |
}</syntaxhighlight> |
||
Both the compile-time and run-time output: |
Both the compile-time and run-time output: |
||
<pre>6 |
<pre>6 |
||
Line 1,008: | Line 1,474: | ||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang="d">main(){ |
||
print(multiply(1,2)); |
print(multiply(1,2)); |
||
print(multiply2(1,2)); |
print(multiply2(1,2)); |
||
Line 1,025: | Line 1,491: | ||
return num1 * num2; |
return num1 * num2; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|dc}}== |
=={{header|dc}}== |
||
For dc, the functions (called macros) are limited to names from 'a' to 'z' |
For dc, the functions (called macros) are limited to names from 'a' to 'z' |
||
Create a function called 'm' |
Create a function called 'm' |
||
<lang |
<syntaxhighlight lang="dc">[*] sm</syntaxhighlight> |
||
Use it (lm loads the function in 'm',x executes it, f shows the the stack.) |
Use it (lm loads the function in 'm',x executes it, f shows the the stack.) |
||
< |
<syntaxhighlight lang="dc">3 4 lm x f |
||
= 12</ |
= 12</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
In addition to what is shown in the section [[#Pascal|Pascal]], the following is possible too: |
|||
<lang Delphi>function Multiply(a, b: Integer): Integer; |
|||
<syntaxhighlight lang="delphi">function multiply(a, b: integer): integer; |
|||
begin |
begin |
||
result := a * b; |
|||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Diego}}== |
|||
<syntaxhighlight lang="diego">begin_funct({number}, multiply)_param({number}, a, b); |
|||
with_funct[]_calc([a]*[b]); |
|||
end_funct[]; |
|||
me_msg()_funct(multiply)_param(1,2);</syntaxhighlight> |
|||
=={{header|DM}}== |
|||
Functions (called procs) may be derived from <code>proc</code>. |
|||
<syntaxhighlight lang="dm">proc/multiply(a, b) |
|||
return a * b |
|||
</syntaxhighlight> |
|||
=={{header|Draco}}== |
=={{header|Draco}}== |
||
Line 1,046: | Line 1,526: | ||
return type of the function. |
return type of the function. |
||
< |
<syntaxhighlight lang="draco">proc multiply(word a, b) word: |
||
a * b |
a * b |
||
corp</ |
corp</syntaxhighlight> |
||
=={{header|Dragon}}== |
=={{header|Dragon}}== |
||
< |
<syntaxhighlight lang="dragon">func multiply(a, b) { |
||
return a*b |
return a*b |
||
}</ |
}</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi">function Multiply(a, b : Integer) : Integer; |
||
begin |
begin |
||
Result := a * b; |
Result := a * b; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">func multiply(a, b) { |
||
a * b |
a * b |
||
}</ |
}</syntaxhighlight> |
||
Using lambda syntax: |
Using lambda syntax: |
||
< |
<syntaxhighlight lang="dyalect">let multiply = (a, b) => a * b</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">multiply a b: |
||
* a b</ |
* a b</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def multiply(a, b) { |
||
return a * b |
return a * b |
||
}</ |
}</syntaxhighlight> |
||
(This does not necessarily return a product, but whatever the "multiply" method of <var>a</var> returns. The parameters could be guarded to only accept standard numbers.) |
(This does not necessarily return a product, but whatever the "multiply" method of <var>a</var> 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: |
It is also possible to write short anonymous function definitions which do not need explicit returns: |
||
< |
<syntaxhighlight lang="e">def multiply := fn a, b { a * b }</syntaxhighlight> |
||
This definition is identical to the previous except that the function object will not know its own name. |
This definition is identical to the previous except that the function object will not know its own name. |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
<syntaxhighlight lang="text"> |
|||
<lang>func multiply a b . r . |
|||
func multiply a b . |
|||
return a * b |
|||
. |
. |
||
print multiply 7 5 |
|||
</syntaxhighlight> |
|||
print res</lang> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(define (multiply a b) (* a b)) → multiply ;; (1) |
(define (multiply a b) (* a b)) → multiply ;; (1) |
||
(multiply 1/3 666) → 222 |
(multiply 1/3 666) → 222 |
||
Line 1,118: | Line 1,599: | ||
multiply → (λ (_a _b) (#🔶_multiply)) ;; compiled function |
multiply → (λ (_a _b) (#🔶_multiply)) ;; compiled function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ecstasy}}== |
|||
<syntaxhighlight lang="java"> |
|||
module MultiplyExample { |
|||
static <Value extends Number> Value multiply(Value n1, Value n2) { |
|||
return n1 * n2; |
|||
} |
|||
void run() { |
|||
(Int i1, Int i2) = (7, 3); |
|||
Int i3 = multiply(i1, i2); |
|||
(Double d1, Double d2) = (2.7182818, 3.1415); |
|||
Double d3 = multiply(d1, d2); |
|||
@Inject Console console; |
|||
console.print($"{i1}*{i2}={i3}, {d1}*{d2}={d3}"); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
7*3=21, 2.7182818*3.1415=8.539482274700001 |
|||
</pre> |
|||
=={{header|Efene}}== |
=={{header|Efene}}== |
||
< |
<syntaxhighlight lang="efene">multiply = fn (A, B) { |
||
A * B |
A * B |
||
} |
} |
||
Line 1,128: | Line 1,632: | ||
run = fn () { |
run = fn () { |
||
io.format("~p~n", [multiply(2, 5)]) |
io.format("~p~n", [multiply(2, 5)]) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
<syntaxhighlight lang="eiffel"> |
|||
<lang Eiffel> |
|||
multiply(a, b: INTEGER): INTEGER |
multiply(a, b: INTEGER): INTEGER |
||
do |
do |
||
Result := a*b |
Result := a*b |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
< |
<syntaxhighlight lang="ela">multiply x y = x * y</syntaxhighlight> |
||
Anonymous function: |
Anonymous function: |
||
< |
<syntaxhighlight lang="ela">\x y -> x * y</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
< |
<syntaxhighlight lang="elena">real multiply(real a, real b) |
||
= a * b;</ |
= a * b;</syntaxhighlight> |
||
Anonymous function / closure: |
Anonymous function / closure: |
||
< |
<syntaxhighlight lang="elena">symbol f = (x,y => x * y);</syntaxhighlight> |
||
Root closure: |
Root closure: |
||
< |
<syntaxhighlight lang="elena">f(x,y){ ^ x * y }</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule RosettaCode do |
||
def multiply(x,y) do |
def multiply(x,y) do |
||
x * y |
x * y |
||
Line 1,160: | Line 1,664: | ||
end |
end |
||
RosettaCode.task</ |
RosettaCode.task</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,168: | Line 1,672: | ||
=={{header|Elm}}== |
=={{header|Elm}}== |
||
<syntaxhighlight lang="elm"> |
|||
<lang Elm> |
|||
--There are multiple ways to create a function in Elm |
--There are multiple ways to create a function in Elm |
||
Line 1,176: | Line 1,680: | ||
--This is an anonymous function |
--This is an anonymous function |
||
\x y -> x*y |
\x y -> x*y |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun multiply (x y) |
||
(* x y))</ |
(* x y))</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="lisp">(defun multiply (x y) |
||
"Return the product of X and Y." |
"Return the product of X and Y." |
||
(* x y))</ |
(* x y))</syntaxhighlight> |
||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
fun multiply = var by var a, var b |
|||
return a * b |
|||
end |
|||
writeLine(multiply(6, 7)) |
|||
writeLine(multiply("can", 2)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
42 |
|||
cancan |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
===Using case, multiple lines=== |
===Using case, multiple lines=== |
||
< |
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel |
||
-module(func_definition). |
-module(func_definition). |
||
-export([main/0]). |
-export([main/0]). |
||
Line 1,201: | Line 1,719: | ||
case {A,B} of |
case {A,B} of |
||
{A, B} -> A * B |
{A, B} -> A * B |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>12 |
<pre>12 |
||
Line 1,207: | Line 1,725: | ||
</pre> |
</pre> |
||
===In a single line=== |
===In a single line=== |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(func_definition). |
-module(func_definition). |
||
-export([main/0]). |
-export([main/0]). |
||
Line 1,215: | Line 1,733: | ||
io :format("~p~n",[K]). |
io :format("~p~n",[K]). |
||
multiply(A,B) -> A * B.</ |
multiply(A,B) -> A * B.</syntaxhighlight> |
||
The output is the same. |
The output is the same. |
||
Line 1,249: | Line 1,767: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function multiply( atom a, atom b ) |
||
return a * b |
return a * b |
||
end function</ |
end function</syntaxhighlight> |
||
If you declare the arguments as <code>object</code> then sequence comprehension kicks in: |
If you declare the arguments as <code>object</code> then sequence comprehension kicks in: |
||
< |
<syntaxhighlight lang="euphoria">function multiply( object a, object b ) |
||
return a * b |
return a * b |
||
end function |
end function |
||
Line 1,264: | Line 1,782: | ||
? multiply( a, b ) |
? multiply( a, b ) |
||
? multiply( a, 7 ) |
? multiply( a, 7 ) |
||
? multiply( 10.39564, b )</ |
? multiply( 10.39564, b )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>81 |
<pre>81 |
||
Line 1,274: | Line 1,792: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
The default will be an integer function but you can specify other types as shown: |
The default will be an integer function but you can specify other types as shown: |
||
< |
<syntaxhighlight lang="fsharp">let multiply x y = x * y // integer |
||
let fmultiply (x : float) (y : float) = x * y</ |
let fmultiply (x : float) (y : float) = x * y</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">: multiply ( a b -- a*b ) * ;</syntaxhighlight> |
||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
< |
<syntaxhighlight lang="falcon">function sayHiTo( name ) |
||
> "Hi ", name |
> "Hi ", name |
||
end</ |
end</syntaxhighlight> |
||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
< |
<syntaxhighlight 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} |
m: {binding the function to one of the 26 available symbol names} |
||
2 3m;! {executing the function, yielding 6}</ |
2 3m;! {executing the function, yielding 6}</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom">class FunctionDefinition |
||
{ |
{ |
||
public static Void main () |
public static Void main () |
||
Line 1,298: | Line 1,816: | ||
echo ("Multiply 2 and 4: ${multiply(2, 4)}") |
echo ("Multiply 2 and 4: ${multiply(2, 4)}") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang="fermat">Func Multiply(a, b) = a*b.</syntaxhighlight> |
||
=={{header|Fexl}}== |
=={{header|Fexl}}== |
||
< |
<syntaxhighlight lang="fexl">\multiply=(\x\y * x y)</syntaxhighlight> |
||
Or if I'm being cheeky: |
Or if I'm being cheeky: |
||
< |
<syntaxhighlight lang="fexl">\multiply=*</syntaxhighlight> |
||
=={{header|Fish}}== |
=={{header|Fish}}== |
||
Functions cannot be named in Fish. However, they can be defined as new stacks that pull a certain number of arguments off the stack that came before. <code>2[</code> says pull 2 values off the stack and put them in a new, separate stack. <code>]</code> says put all remaining values in the current stack onto the top of the stack below (the old stack). |
Functions cannot be named in Fish. However, they can be defined as new stacks that pull a certain number of arguments off the stack that came before. <code>2[</code> says pull 2 values off the stack and put them in a new, separate stack. <code>]</code> says put all remaining values in the current stack onto the top of the stack below (the old stack). |
||
<lang |
<syntaxhighlight lang="fish">2[*]</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: fmultiply ( F: a b -- F: c ) F* ; |
||
: multiply ( a b -- c ) * ;</ |
: multiply ( a b -- c ) * ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In FORTRAN I (1957), inline function could be defined at the beginning of the program. Let's note than to specify a floating point real the name of the statement function begins with an X (no type declaration) and to specify this is a function the name ends with a F. |
In FORTRAN I (1957), inline function could be defined at the beginning of the program. Let's note than to specify a floating point real the name of the statement function begins with an X (no type declaration) and to specify this is a function the name ends with a F. |
||
< |
<syntaxhighlight lang="fortran"> XMULTF(X,Y)=X*Y</syntaxhighlight> |
||
And for interger multiplication: |
And for interger multiplication: |
||
< |
<syntaxhighlight lang="fortran"> MULTF(I,J)=I*J</syntaxhighlight> |
||
In FORTRAN IV, FORTRAN 66 or later, define a function: |
In FORTRAN IV, FORTRAN 66 or later, define a function: |
||
< |
<syntaxhighlight lang="fortran">FUNCTION MULTIPLY(X,Y) |
||
REAL MULTIPLY, X, Y |
REAL MULTIPLY, X, Y |
||
MULTIPLY = X * Y |
MULTIPLY = X * Y |
||
END</ |
END</syntaxhighlight> |
||
And for integer multiplication: |
And for integer multiplication: |
||
< |
<syntaxhighlight lang="fortran">FUNCTION MULTINT(X,Y) |
||
INTEGER MULTINT, X, Y |
INTEGER MULTINT, X, Y |
||
MULTINT = X * Y |
MULTINT = X * Y |
||
END</ |
END</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="fortran">module elemFunc |
||
contains |
contains |
||
elemental function multiply(x, y) |
elemental function multiply(x, y) |
||
Line 1,341: | Line 1,859: | ||
multiply = x * y |
multiply = x * y |
||
end function multiply |
end function multiply |
||
end module elemFunc</ |
end module elemFunc</syntaxhighlight> |
||
< |
<syntaxhighlight lang="fortran">program funcDemo |
||
use elemFunc |
use elemFunc |
||
Line 1,351: | Line 1,869: | ||
z = multiply(x,y) ! element-wise invocation only works with elemental function |
z = multiply(x,y) ! element-wise invocation only works with elemental function |
||
end program funcDemo</ |
end program funcDemo</syntaxhighlight> |
||
It is worth noting that Fortran can call functions (and subroutines) using named arguments; e.g. we can call multiply in the following way: |
It is worth noting that Fortran can call functions (and subroutines) using named arguments; e.g. we can call multiply in the following way: |
||
< |
<syntaxhighlight 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)</ |
z = multiply(y=x, x=y) ! the same as multiply(y, x)</syntaxhighlight> |
||
(Because of commutativity property of the multiplication, the difference between <code>multiply(x,y)</code> and <code>multiply(y,x)</code> is not evident) |
(Because of commutativity property of the multiplication, the difference between <code>multiply(x,y)</code> and <code>multiply(y,x)</code> is not evident) |
||
Also note that the function result can be declared with a different name within the routine: |
Also note that the function result can be declared with a different name within the routine: |
||
< |
<syntaxhighlight lang="fortran">module elemFunc |
||
contains |
contains |
||
elemental function multiply(x, y) result(z) |
elemental function multiply(x, y) result(z) |
||
Line 1,365: | Line 1,883: | ||
z = x * y |
z = x * y |
||
end function multiply |
end function multiply |
||
end module elemFunc</ |
end module elemFunc</syntaxhighlight> |
||
=={{header| |
=={{header|Free Pascal}}== |
||
Free Pascal allows everything what [[#Delphi|Delphi]] allows. |
|||
<lang freebasic>' FB 1.05.0 Win64 |
|||
Note, using the special variable “<tt>result</tt>” requires <tt>{$modeSwitch result+}</tt>. |
|||
This is the default in <tt>{$mode objFPC}</tt> and <tt>{$mode Delphi}</tt>. |
|||
Furthermore, after the assignment to the return variable further statements may follow. |
|||
Function multiply(d1 As Double, d2 As Double) As Double |
|||
To ensure a value is returned immediately and no further following statements are processed, using the built-in <tt>exit</tt> procedure is possible too in <tt>{$mode objFPC}</tt>: |
|||
Return d1 * d2 |
|||
<syntaxhighlight lang="delphi">function multiply(a, b: integer): integer; |
|||
End Function</lang> |
|||
begin |
|||
This function could either be used for all numeric types (as they are implicitly convertible to Double) |
|||
exit(a * b); |
|||
or could be overloaded to deal with each such type (there are 12 of them). |
|||
end;</syntaxhighlight> |
|||
If <tt>exit</tt> has been redefined in the current scope, its special meaning can be accessed via the fully-qualified identifier <tt>system.exit</tt>. |
|||
Alternatively, one could write a macro though this wouldn't be type-safe: |
|||
Note, any enclosing <tt>finally</tt> frames of <tt>try … finally … end</tt> are processed first before actually returning from the <tt>function</tt>. |
|||
As a consequence of that, <tt>exit</tt> may not appear within a <tt>finally</tt> frame. |
|||
<lang freebasic>#Define multiply(d1, d2) (d1) * (d2)</lang> |
|||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
This function works correctly with any combination of arbitrarily-large integers, arbitrary-precision floating point numbers, arbitrary-size rational numbers, complex numbers, intervals of real numbers, and even numbers with units of measure (e.g. <code>multiply[1 watt, 1 s]</code> gives an answer with dimensions of energy. Frink tries hard to always Do The Right Thing with math and numerics and units of measure. |
|||
<lang frink>multiply[x,y] := x*y</lang> |
|||
<syntaxhighlight lang="frink">multiply[x,y] := x*y</syntaxhighlight> |
|||
=={{header|Futhark}}== |
=={{header|Futhark}}== |
||
<syntaxhighlight lang="futhark"> |
|||
<lang Futhark> |
|||
let multiply (x: i32, y: i32) : i32 = x * y |
let multiply (x: i32, y: i32) : i32 = x * y |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FutureBasic}}== |
|||
<lang futurebasic> |
|||
include "ConsoleWindow" |
|||
local fn multiply( a as long, b as long ) as long |
|||
end fn = a * b |
|||
print fn multiply( 3, 9 ) |
|||
</lang> |
|||
Output: |
|||
<pre> |
|||
27 |
|||
</pre> |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=bc93236474d9937217dd4117026f7441 Click this link to run this code]''' |
|||
<lang gambas>Public Sub Main() |
|||
Print Multiply(56, 4.66) |
|||
End |
|||
Public Sub Multiply(f1 As Float, f2 As Float) As Float |
|||
Return f1 * f2 |
|||
End</lang> |
|||
Output: |
|||
<pre> |
|||
260.96 |
|||
</pre> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">multiply := function(a, b) |
||
return a*b; |
return a*b; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|GML}}== |
=={{header|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: |
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: |
||
< |
<syntaxhighlight lang="gml">#define multiply |
||
a = argument0 |
a = argument0 |
||
b = argument1 |
b = argument1 |
||
return(a * b)</ |
return(a * b)</syntaxhighlight> |
||
=={{header|Gnuplot}}== |
=={{header|Gnuplot}}== |
||
< |
<syntaxhighlight lang="gnuplot">multiply(x,y) = x*y |
||
# then for example |
# then for example |
||
print multiply(123,456)</ |
print multiply(123,456)</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
Line 1,443: | Line 1,932: | ||
The return statement can contain an expression of the function return type: |
The return statement can contain an expression of the function return type: |
||
< |
<syntaxhighlight lang="go">func multiply(a, b float64) float64 { |
||
return a * b |
return a * b |
||
}</ |
}</syntaxhighlight> |
||
Alternatively, if the return value is named, the return statement does not require an expression: |
Alternatively, if the return value is named, the return statement does not require an expression: |
||
< |
<syntaxhighlight lang="go">func multiply(a, b float64) (z float64) { |
||
z = a * b |
z = a * b |
||
return |
return |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Golfscript}}== |
=={{header|Golfscript}}== |
||
<lang |
<syntaxhighlight lang="golfscript">{*}:multiply;</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">def multiply = { x, y -> x * y }</syntaxhighlight> |
||
Test Program: |
Test Program: |
||
< |
<syntaxhighlight lang="groovy">println "x * y = 20 * 50 = ${multiply 20, 50}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>x * y = 20 * 50 = 1000</pre> |
<pre>x * y = 20 * 50 = 1000</pre> |
||
=={{header|Halon}}== |
=={{header|Halon}}== |
||
< |
<syntaxhighlight lang="halon">function multiply( $a, $b ) |
||
{ |
{ |
||
return $a * $b; |
return $a * $b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">multiply x y = x * y</syntaxhighlight> |
||
Alternatively, with help of auto-currying, |
Alternatively, with help of auto-currying, |
||
< |
<syntaxhighlight lang="haskell">multiply = (*)</syntaxhighlight> |
||
You can use [[lambda-function]] |
You can use [[lambda-function]] |
||
< |
<syntaxhighlight lang="haskell">multiply = \ x y -> x*y</syntaxhighlight> |
||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">function multiply(x:Float, y:Float):Float{ |
||
return x * y; |
return x * y; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|hexiscript}}== |
=={{header|hexiscript}}== |
||
< |
<syntaxhighlight lang="hexiscript">fun multiply a b |
||
return a * b |
return a * b |
||
endfun</ |
endfun</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">FUNCTION multiply(a, b) |
||
multiply = a * b |
multiply = a * b |
||
END</ |
END</syntaxhighlight> |
||
=={{header|HolyC}}== |
=={{header|HolyC}}== |
||
< |
<syntaxhighlight lang="holyc">F64 Multiply(F64 a, F64 b) { |
||
return a * b; |
return a * b; |
||
} |
} |
||
Line 1,497: | Line 1,986: | ||
F64 x; |
F64 x; |
||
x = Multiply(42, 13.37); |
x = Multiply(42, 13.37); |
||
Print("%5.2f\n", x);</ |
Print("%5.2f\n", x);</syntaxhighlight> |
||
=={{header|Hy}}== |
=={{header|Hy}}== |
||
Function definition: |
Function definition: |
||
< |
<syntaxhighlight lang="clojure">(defn multiply [a b] |
||
(* a b))</ |
(* a b))</syntaxhighlight> |
||
Lambda definition: |
Lambda definition: |
||
< |
<syntaxhighlight lang="clojure">(def multiply (fn [a b] (* a b)))</syntaxhighlight> |
||
=={{header|i}}== |
=={{header|i}}== |
||
<syntaxhighlight lang="i"> |
|||
<lang i> |
|||
concept multiply(a, b) { |
concept multiply(a, b) { |
||
return a*b |
return a*b |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure multiply(a,b) |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
The task description is unclear on what to do when the arguments to the function are non-scalar, so here's multiple versions: |
The task description is unclear on what to do when the arguments to the function are non-scalar, so here's multiple versions: |
||
< |
<syntaxhighlight lang="idl">function multiply ,a,b |
||
return, a* b |
return, a* b |
||
end</ |
end</syntaxhighlight> |
||
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". |
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: |
Alternatively, there's this possibility: |
||
< |
<syntaxhighlight lang="idl">function multiply ,a,b |
||
return, product([a, b]) |
return, product([a, b]) |
||
end</ |
end</syntaxhighlight> |
||
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. |
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: |
Finally, there's this option: |
||
< |
<syntaxhighlight lang="idl">function multiply ,a,b |
||
return, a # b |
return, a # b |
||
end</ |
end</syntaxhighlight> |
||
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 6}}== |
=={{header|Inform 6}}== |
||
< |
<syntaxhighlight lang="inform6">[ multiply a b; |
||
return a * b; |
return a * b; |
||
];</ |
];</syntaxhighlight> |
||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
< |
<syntaxhighlight lang="inform7">To decide which number is (A - number) multiplied by (B - number): |
||
decide on A * B.</ |
decide on A * B.</syntaxhighlight> |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<syntaxhighlight lang="io">multiply := method(a,b,a*b)</syntaxhighlight> |
||
=={{header|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) |
|||
PRINT |
|||
'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) |
|||
PRINT |
|||
'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)) |
|||
PRINT |
|||
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> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j">multiply=: *</syntaxhighlight> |
||
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. |
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): |
Or, more verbosely (and a bit slower, though the speed difference should be unnoticeable in most contexts): |
||
< |
<syntaxhighlight lang="j">multiply=: dyad define |
||
x * y |
x * y |
||
)</ |
)</syntaxhighlight> |
||
Here we use an [http://www.jsoftware.com/help/dictionary/intro18.htm explicit] definition (where the arguments are named) rather than a [http://www.jsoftware.com/help/dictionary/intro19.htm tacit] version (where the arguments are implied). In explicit J verbs, x is the left argument and y is the right argument. |
Here we use an [http://www.jsoftware.com/help/dictionary/intro18.htm explicit] definition (where the arguments are named) rather than a [http://www.jsoftware.com/help/dictionary/intro19.htm tacit] version (where the arguments are implied). In explicit J verbs, x is the left argument and y is the right argument. |
||
Line 1,664: | Line 2,052: | ||
=={{header|Java}}== |
=={{header|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. |
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. |
||
< |
<syntaxhighlight lang="java">public class Math |
||
{ |
{ |
||
public static int multiply( int a, int b) { return a*b; } |
public static int multiply( int a, int b) { return a*b; } |
||
public static double multiply(double a, double b) { return a*b; } |
public static double multiply(double a, double b) { return a*b; } |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
===Using Java version 8=== |
|||
Since version 8, Java has various built in Functions with their normal mathematical names. |
|||
<syntaxhighlight lang="java"> |
|||
import java.util.function.BiFunction; |
|||
import java.util.function.DoubleUnaryOperator; |
|||
import java.util.function.Function; |
|||
import java.util.function.Predicate; |
|||
import java.util.function.UnaryOperator; |
|||
public final class FunctionDefinition { |
|||
public static void main(String[] args) { |
|||
System.out.println(size.apply("Rosetta")); |
|||
System.out.println(greeting.apply("Joe")); |
|||
System.out.println(half.applyAsDouble(7)); |
|||
System.out.println(lessThanTen.test(15)); |
|||
System.out.println(add.apply(2, 3)); |
|||
} |
|||
private static Function<String, Integer> size = s -> s.length(); |
|||
private static UnaryOperator<String> greeting = s -> "Hello " + s; |
|||
private static DoubleUnaryOperator half = a -> a / 2; |
|||
private static Predicate<Integer> lessThanTen = a -> a < 10; |
|||
private static BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
7 |
|||
Hello Joe |
|||
3.5 |
|||
false |
|||
5 |
|||
</pre> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES1-*=== |
===ES1-*=== |
||
Function Declaration |
Function Declaration |
||
< |
<syntaxhighlight lang="javascript">function multiply(a, b) { |
||
return a*b; |
return a*b; |
||
}</ |
}</syntaxhighlight> |
||
===ES3-*=== |
===ES3-*=== |
||
Function Expression |
Function Expression |
||
< |
<syntaxhighlight lang="javascript">var multiply = function(a, b) { |
||
return a * b; |
return a * b; |
||
};</ |
};</syntaxhighlight> |
||
Named Function Expression |
Named Function Expression |
||
< |
<syntaxhighlight lang="javascript">var multiply = function multiply(a, b) { |
||
return a * b; |
return a * b; |
||
};</ |
};</syntaxhighlight> |
||
Method Definition |
Method Definition |
||
< |
<syntaxhighlight lang="javascript">var o = { |
||
multiply: function(a, b) { |
multiply: function(a, b) { |
||
return a * b; |
return a * b; |
||
} |
} |
||
};</ |
};</syntaxhighlight> |
||
===ES5-*=== |
===ES5-*=== |
||
Accessors |
Accessors |
||
< |
<syntaxhighlight lang="javascript">var o = { |
||
get foo() { |
get foo() { |
||
return 1; |
return 1; |
||
Line 1,704: | Line 2,133: | ||
// do things with value |
// do things with value |
||
} |
} |
||
};</ |
};</syntaxhighlight> |
||
===ES6-*=== |
===ES6-*=== |
||
Arrow Function |
Arrow Function |
||
< |
<syntaxhighlight lang="javascript">var multiply = (a, b) => a * b; |
||
var multiply = (a, b) => { return a * b }; |
var multiply = (a, b) => { return a * b }; |
||
</lang> |
|||
// Or, `var` being long deprecated, and currying convenient, |
|||
// (particularly in use with the higher-order Array methods) |
|||
const multiply = a => |
|||
b => a * b; |
|||
</syntaxhighlight> |
|||
Concise Body Method Definition |
Concise Body Method Definition |
||
< |
<syntaxhighlight lang="javascript">var o = { |
||
multiply(a, b) { |
multiply(a, b) { |
||
return a * b; |
return a * b; |
||
} |
} |
||
};</ |
};</syntaxhighlight> |
||
Generator Functions |
Generator Functions |
||
< |
<syntaxhighlight lang="javascript">function * generator() { |
||
yield 1; |
yield 1; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
< |
<syntaxhighlight lang="joy">DEFINE multiply == * .</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Example of a simple function definition:< |
Example of a simple function definition:<syntaxhighlight lang="jq">def multiply(a; b): a*b;</syntaxhighlight> |
||
Example of the definition of an inner function:< |
Example of the definition of an inner function:<syntaxhighlight lang="jq"># 2 | generate(. * .) will generate 2, 4, 16, 256, ... |
||
def generate(f): def r: ., (f | r); r;</ |
def generate(f): def r: ., (f | r); r;</syntaxhighlight> |
||
The previous example (generate/1) also illustrates that a function argument can be a function or composition of functions. Here is another example:< |
The previous example (generate/1) also illustrates that a function argument can be a function or composition of functions. Here is another example:<syntaxhighlight lang="jq">def summation(f): reduce .[] as $x (0; . + ($x|f));</syntaxhighlight> |
||
<tt>summation/1</tt> 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:< |
<tt>summation/1</tt> 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:<syntaxhighlight lang="jq">summation( .h * .w)</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 1,739: | Line 2,174: | ||
General function definition: |
General function definition: |
||
< |
<syntaxhighlight lang="julia">function multiply(a::Number, b::Number) |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
Julia also supports `assignment` definition as shorthand: |
Julia also supports `assignment` definition as shorthand: |
||
< |
<syntaxhighlight lang="julia">multiply(a, b) = a * b</syntaxhighlight> |
||
And lambda calculus: |
And lambda calculus: |
||
< |
<syntaxhighlight lang="julia">multiply = (a, b) -> a * b</syntaxhighlight> |
||
=={{header|Kaya}}== |
=={{header|Kaya}}== |
||
< |
<syntaxhighlight lang="kaya">program test; |
||
// A function definition in Kaya: |
// A function definition in Kaya: |
||
Line 1,762: | Line 2,197: | ||
Void main() { |
Void main() { |
||
putStrLn(string( multiply(2, 3) )); |
putStrLn(string( multiply(2, 3) )); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Klingphix}}== |
=={{header|Klingphix}}== |
||
< |
<syntaxhighlight lang="klingphix">:multiply * ; |
||
2 3 multiply print { 6 }</ |
2 3 multiply print { 6 }</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="kotlin">// One-liner |
||
fun multiply(a: Int, b: Int) = a * b |
fun multiply(a: Int, b: Int) = a * b |
||
Line 1,776: | Line 2,211: | ||
fun multiplyProper(a: Int, b: Int): Int { |
fun multiplyProper(a: Int, b: Int): Int { |
||
return a * b |
return a * b |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
{def multiply |
{def multiply |
||
{lambda {:a :b} |
{lambda {:a :b} |
||
Line 1,796: | Line 2,231: | ||
-> 720 |
-> 720 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|Lang}}== |
||
=== Function decleration === |
|||
A function body may use curly braces, but it is not required if it is a single expression. |
|||
<syntaxhighlight lang="lang"> |
|||
fp.multiply = ($a, $b) -> { |
|||
return parser.op($a * $b) |
|||
} |
|||
</syntaxhighlight> |
|||
=== One-line function decleration === |
|||
A return statement may be used, but a function's last value is its implicit return value. |
|||
<syntaxhighlight lang="lang"> |
|||
fp.multiply = ($a, $b) -> return parser.op($a * $b) |
|||
</syntaxhighlight> |
|||
=== Function decleration by using operator functions === |
|||
Functions defined with explicit parameters may be closures, and those defined with implied parameters are not. |
|||
<syntaxhighlight lang="lang"> |
|||
fp.multiply = fn.mul |
|||
</syntaxhighlight> |
|||
=== Function decleration by using combinator functions === |
|||
Langur functions are first-order. They are pure in terms of setting values, though not in terms of I/O. |
|||
Combinator functions can be called partially, fn.argCnt2 is used to force the caller to provide 2 arguments to prevent partially calling fp.multiply |
|||
<syntaxhighlight lang="lang"> |
|||
fp.multiply = fn.argCnt2(fn.combA2(fn.mul)) |
|||
</syntaxhighlight> |
|||
=== Function decleration with call by pointer === |
|||
=== explicit parameters === |
|||
<syntaxhighlight lang="lang"> |
|||
Explicit parameters are defined with parentheses after the f token, with no spacing. To specify no parameters, use an empty set of parentheses. |
|||
fp.multiply = ($[a], $[b]) -> { |
|||
return parser.op($*a * $*b) # Pointers can be dereferenced by using * |
|||
.multiply(3, 4)</lang> |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|langur}}== |
|||
=== implied parameters === |
|||
<syntaxhighlight> |
|||
Parameters are implied when the f token is not immediately followed by parentheses without spacing. The implied order of implied parameters is based on the string sort order of their names, not their order within the function. |
|||
val multiply = fn{*} |
|||
</syntaxhighlight> |
|||
.multiply(3, 4)</lang> |
|||
=== operator implied functions === |
|||
Operator implied functions are built using an infix operator between curly braces on an f token. |
|||
{{works with|langur|0.6.6}} |
|||
<lang langur>val .multiply = f{x} |
|||
.multiply(3, 4)</lang> |
|||
<syntaxhighlight> |
|||
=== nil left partially implied functions === |
|||
val multiply = fn a, b: a * b |
|||
These are built with an infix operator and one operand inside the f{...} tokens. |
|||
</syntaxhighlight> |
|||
<syntaxhighlight> |
|||
{{works with|langur|0.8.11}} |
|||
val multiply = fn(a, b) { a * b } |
|||
</syntaxhighlight> |
|||
map .times3, [1, 2, 3]</lang> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
Line 1,835: | Line 2,281: | ||
Lasso supports multiple dispatch — signature definitions determine which method will be invoked. |
Lasso supports multiple dispatch — signature definitions determine which method will be invoked. |
||
< |
<syntaxhighlight lang="lasso">define multiply(a,b) => { |
||
return #a * #b |
return #a * #b |
||
}</ |
}</syntaxhighlight> |
||
As this function is so simple it can also be represented like so: |
As this function is so simple it can also be represented like so: |
||
< |
<syntaxhighlight lang="lasso">define multiply(a,b) => #a * #b</syntaxhighlight> |
||
Using multiple dispatch, different functions will be invoked depending on the functions input. |
Using multiple dispatch, different functions will be invoked depending on the functions input. |
||
< |
<syntaxhighlight lang="lasso">// Signatures that convert second input to match first input |
||
define multiply(a::integer,b::any) => #a * integer(#b) |
define multiply(a::integer,b::any) => #a * integer(#b) |
||
define multiply(a::decimal,b::any) => #a * decimal(#b) |
define multiply(a::decimal,b::any) => #a * decimal(#b) |
||
// Catch all signature |
// Catch all signature |
||
define multiply(a::any,b::any) => decimal(#a) * decimal(#b)</ |
define multiply(a::any,b::any) => decimal(#a) * decimal(#b)</syntaxhighlight> |
||
=={{header|Latitude}}== |
=={{header|Latitude}}== |
||
Line 1,856: | Line 2,302: | ||
Latitude methods are defined using curly braces <code>{}</code> and assigned to variables like any other value. Arguments are implicitly named <code>$1</code>, <code>$2</code>, etc. |
Latitude methods are defined using curly braces <code>{}</code> and assigned to variables like any other value. Arguments are implicitly named <code>$1</code>, <code>$2</code>, etc. |
||
< |
<syntaxhighlight lang="latitude">multiply := { $1 * $2. }.</syntaxhighlight> |
||
Calling a method is done either with parentheses or with a colon. |
Calling a method is done either with parentheses or with a colon. |
||
< |
<syntaxhighlight lang="latitude">multiply (2, 3). |
||
multiply: 2, 3.</ |
multiply: 2, 3.</syntaxhighlight> |
||
If a method is intended to be used as a first-class value or stored in a data structure, the automatic evaluation behavior of methods can be undesired. In this case, one can wrap a method in a <code>Proc</code> with the <code>proc</code> method. <code>Proc</code> objects can then be later called explicitly with <code>call</code>. |
If a method is intended to be used as a first-class value or stored in a data structure, the automatic evaluation behavior of methods can be undesired. In this case, one can wrap a method in a <code>Proc</code> with the <code>proc</code> method. <code>Proc</code> objects can then be later called explicitly with <code>call</code>. |
||
< |
<syntaxhighlight lang="latitude">multiply := proc { $1 * $2. }. |
||
multiply call (2, 3). |
multiply call (2, 3). |
||
multiply call: 2, 3.</ |
multiply call: 2, 3.</syntaxhighlight> |
||
=={{header| |
=={{header|LDPL}}== |
||
<syntaxhighlight lang="ldpl">data: |
|||
<lang lisp> |
|||
n is number |
|||
(defun mutiply (a b) |
|||
(* a b)) |
|||
</lang> |
|||
procedure: |
|||
=={{header|Liberty BASIC}}== |
|||
sub multiply |
|||
<lang lb>' define & call a function |
|||
parameters: |
|||
x is number |
|||
y is number |
|||
result is number |
|||
procedure: |
|||
in result solve x * y |
|||
end sub |
|||
# call the bare sub-procedure |
|||
print multiply( 3, 1.23456) |
|||
call multiply with 3 4 n |
|||
display n lf |
|||
# create a statement for it |
|||
wait |
|||
create statement "multiply $ by $ in $" executing multiply |
|||
multiply 3 by 4 in n |
|||
display n lf |
|||
multiply =m1 *m2 |
|||
</syntaxhighlight> |
|||
end function |
|||
{{out}} |
|||
<pre> |
|||
12 |
|||
12 |
|||
</pre> |
|||
=={{header|LFE}}== |
|||
end</lang> |
|||
<syntaxhighlight lang="lisp"> |
|||
(defun mutiply (a b) |
|||
(* a b)) |
|||
</syntaxhighlight> |
|||
=={{header|Lily}}== |
=={{header|Lily}}== |
||
< |
<syntaxhighlight lang="lily">define multiply(a: Integer, b: Integer): Integer |
||
{ |
{ |
||
return a * b |
return a * b |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">on multiply (a, b) |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
LiveCode has a built-in method called multiply, so there is an extra y to avoid an error. |
LiveCode has a built-in method called multiply, so there is an extra y to avoid an error. |
||
< |
<syntaxhighlight lang="livecode">function multiplyy n1 n2 |
||
return n1 * n2 |
return n1 * n2 |
||
end multiplyy |
end multiplyy |
||
put multiplyy(2,5) -- = 10</ |
put multiplyy(2,5) -- = 10</syntaxhighlight> |
||
=={{header|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. |
|||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to multiply :x :y |
||
output :x * :y |
output :x * :y |
||
end</ |
end</syntaxhighlight> |
||
=={{header|LSE64}}== |
=={{header|LSE64}}== |
||
< |
<syntaxhighlight lang="lse64">multiply : * |
||
multiply. : *. # floating point</ |
multiply. : *. # floating point</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function multiply( a, b ) |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
< |
<syntaxhighlight lang="lucid">multiply(x,y) = x * y</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
===A Module can return value=== |
===A Module can return value=== |
||
A module can return value to stack of values. Calling a module we place parent stack to module, so we can read any value. |
A module can return value to stack of values. Calling a module we place parent stack to module, so we can read any value. |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
Module Multiply (a, b) { |
Module Multiply (a, b) { |
||
Line 1,964: | Line 2,422: | ||
Call Checkit, 20, 50 |
Call Checkit, 20, 50 |
||
Print Number=1000 |
Print Number=1000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===A Local Function Definition=== |
===A Local Function Definition=== |
||
There are two types of function, the normal and the lambda. If a Function return string then we have to use $ at the end of function name. |
There are two types of function, the normal and the lambda. If a Function return string then we have to use $ at the end of function name. |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
\\ functions can shange by using a newer definition |
\\ functions can shange by using a newer definition |
||
Line 2,035: | Line 2,493: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
===A Lambda Function=== |
===A Lambda Function=== |
||
Lambda function is first citizen. We can push it to stack and make another reading from stack. Lambda can use closures as static variables, some of them are pointers so if we copy a lambda we just copy the pointer. Pointers are containers like pointer to array, inventory and stack. Here we define string lambda function (there is a numeric also) |
Lambda function is first citizen. We can push it to stack and make another reading from stack. Lambda can use closures as static variables, some of them are pointers so if we copy a lambda we just copy the pointer. Pointers are containers like pointer to array, inventory and stack. Here we define string lambda function (there is a numeric also) |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckIt { |
Module CheckIt { |
||
A$=Lambda$ N$="Hello There" (x) ->{ |
A$=Lambda$ N$="Hello There" (x) ->{ |
||
Line 2,062: | Line 2,520: | ||
B$=List$("Hello", "Rosetta", "Function") |
B$=List$("Hello", "Rosetta", "Function") |
||
Print B$(1)="Hello" |
Print B$(1)="Hello" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">define(`multiply',`eval($1*$2)') |
||
multiply(2,3)</ |
multiply(2,3)</syntaxhighlight> |
||
=={{header|MAD}}== |
=={{header|MAD}}== |
||
MAD supports two types of function declarations. One simply evaluates an expression: |
MAD supports two types of function declarations. One simply evaluates an expression: |
||
< |
<syntaxhighlight lang="mad"> INTERNAL FUNCTION MULT.(A,B) = A * B</syntaxhighlight> |
||
Another allows multiple lines to be executed: |
Another allows multiple lines to be executed: |
||
< |
<syntaxhighlight lang="mad"> INTERNAL FUNCTION(A, B) |
||
ENTRY TO MULT. |
ENTRY TO MULT. |
||
FUNCTION RETURN A * B |
FUNCTION RETURN A * B |
||
END OF FUNCTION</ |
END OF FUNCTION</syntaxhighlight> |
||
There are several quirks here. First, the length of any identifier must not be longer than six |
There are several quirks here. First, the length of any identifier must not be longer than six |
||
Line 2,093: | Line 2,551: | ||
=={{header|Make}}== |
=={{header|Make}}== |
||
In makefile, a function may be defined as a rule, with recursive make used to retrieve the returned value. |
In makefile, a function may be defined as a rule, with recursive make used to retrieve the returned value. |
||
< |
<syntaxhighlight lang="make">A=1 |
||
B=1 |
B=1 |
||
multiply: |
multiply: |
||
@expr $(A) \* $(B)</ |
@expr $(A) \* $(B)</syntaxhighlight> |
||
Invoking it |
Invoking it |
||
< |
<syntaxhighlight lang="make">make -f mul.mk multiply A=100 B=3 |
||
> 300</ |
> 300</syntaxhighlight> |
||
Using gmake, the define syntax is used to define a new function |
Using gmake, the define syntax is used to define a new function |
||
{{works with|gmake}} |
{{works with|gmake}} |
||
< |
<syntaxhighlight lang="make">A=1 |
||
B=1 |
B=1 |
||
Line 2,113: | Line 2,571: | ||
@$(call multiply, $(A), $(B)) |
@$(call multiply, $(A), $(B)) |
||
|gmake -f mul.mk do A=5 B=3</ |
|gmake -f mul.mk do A=5 B=3</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">multiply:= (a, b) -> a * b;</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Line 2,122: | Line 2,580: | ||
Defining a function as a transformation rule: |
Defining a function as a transformation rule: |
||
< |
<syntaxhighlight lang="mathematica">multiply[a_,b_]:=a*b</syntaxhighlight> |
||
Defining a pure function: |
Defining a pure function: |
||
< |
<syntaxhighlight lang="mathematica">multiply=#1*#2&</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">f(a, b):= a*b;</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">fn multiply a b = |
||
( |
( |
||
a * b |
a * b |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury">% Module ceremony elided... |
||
:- func multiply(integer, integer) = integer. |
:- func multiply(integer, integer) = integer. |
||
multiply(A, B) = A * B.</ |
multiply(A, B) = A * B.</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|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 <code>primarydef</code>. |
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 <code>primarydef</code>. |
||
< |
<syntaxhighlight lang="metafont">primarydef a mult b = a * b enddef;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="metafont">t := 3 mult 5; show t; end</syntaxhighlight> |
||
The '''primarydef''' allows to build binary operators with the same priority as *. For a more generic macro, we can use instead |
The '''primarydef''' allows to build binary operators with the same priority as *. For a more generic macro, we can use instead |
||
< |
<syntaxhighlight lang="metafont">def mult(expr a, b) = (a * b) enddef; |
||
t := mult(2,3); |
t := mult(2,3); |
||
show t; |
show t; |
||
end</ |
end</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
<code>'*</code> is syntax sugar for <code>(*)</code>, which is an anonymous function that takes two numbers from the data stack, multiplies them, and leaves the result on the data stack. To give it a name, we can use the <code>:</code> sigil which is syntax sugar for <code>define</code>. |
<code>'*</code> is syntax sugar for <code>(*)</code>, which is an anonymous function that takes two numbers from the data stack, multiplies them, and leaves the result on the data stack. To give it a name, we can use the <code>:</code> sigil which is syntax sugar for <code>define</code>. |
||
<lang |
<syntaxhighlight lang="min">'* :multiply</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">multiply = function(x,y) |
||
return x*y |
return x*y |
||
end function |
end function |
||
print multiply(6, 7)</ |
print multiply(6, 7)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>42</pre> |
<pre>42</pre> |
||
Line 2,177: | Line 2,635: | ||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">PROCEDURE Multiply(a, b: INTEGER): INTEGER; |
||
BEGIN |
BEGIN |
||
RETURN a * b |
RETURN a * b |
||
END Multiply;</ |
END Multiply;</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">PROCEDURE Multiply(a, b: INTEGER): INTEGER = |
||
BEGIN |
BEGIN |
||
RETURN a * b; |
RETURN a * b; |
||
END Multiply;</ |
END Multiply;</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<syntaxhighlight lang="mumps">MULTIPLY(A,B);Returns the product of A and B |
||
QUIT A*B</ |
QUIT A*B</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang="nanoquery">def multiply(a, b) |
||
return a * b |
return a * b |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
< |
<syntaxhighlight lang="neko">var multiply = function(a, b) { |
||
a * b |
a * b |
||
} |
} |
||
$print(multiply(2, 3))</ |
$print(multiply(2, 3))</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
Line 2,208: | Line 2,666: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight 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 |
def multiply(a, b) { return a * b } // this is a local function, can take advantage of type inference |
||
return multiply(a, b) |
return multiply(a, b) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NESL}}== |
=={{header|NESL}}== |
||
< |
<syntaxhighlight lang="nesl">function multiply(x, y) = x * y;</syntaxhighlight> |
||
The NESL system responds by reporting the type it has inferred for the function: |
The NESL system responds by reporting the type it has inferred for the function: |
||
<pre>multiply = fn : (a, a) -> a :: (a in number)</pre> |
<pre>multiply = fn : (a, a) -> a :: (a in number)</pre> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols binary |
options replace format comments java crossref savelog symbols binary |
||
Line 2,242: | Line 2,700: | ||
product = multiplicand * multiplier |
product = multiplicand * multiplier |
||
return product</ |
return product</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,251: | Line 2,709: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">> (define (my-multiply a b) (* a b)) |
||
(lambda (a b) (* a b)) |
(lambda (a b) (* a b)) |
||
> (my-multiply 2 3) |
> (my-multiply 2 3) |
||
6</ |
6</syntaxhighlight> |
||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
Using variables |
Using variables |
||
< |
<syntaxhighlight lang="nial">multiply is operation a b {a * b}</syntaxhighlight> |
||
Using it |
Using it |
||
< |
<syntaxhighlight lang="nial">|multiply 2 3 |
||
=6</ |
=6</syntaxhighlight> |
||
Point free form |
Point free form |
||
<lang |
<syntaxhighlight lang="nial">mul is *</syntaxhighlight> |
||
Using it |
Using it |
||
< |
<syntaxhighlight lang="nial">|mul 3 4 |
||
=12</ |
=12</syntaxhighlight> |
||
Nial also allows creation of operators |
Nial also allows creation of operators |
||
< |
<syntaxhighlight lang="nial">multiply is op a b {a * b}</syntaxhighlight> |
||
Using it. |
Using it. |
||
< |
<syntaxhighlight lang="nial">|2 multiply 3 |
||
=6 |
=6 |
||
|multiply 2 3 |
|multiply 2 3 |
||
=6</ |
=6</syntaxhighlight> |
||
Since this is an array programming language, any parameters can be arrays too |
Since this is an array programming language, any parameters can be arrays too |
||
< |
<syntaxhighlight lang="nial">|mul 3 [1,2] |
||
=3 6 |
=3 6 |
||
|mul [1,2] [10,20] |
|mul [1,2] [10,20] |
||
=10 40</ |
=10 40</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Nim has a magic variable, `result`, which can be used as a substitute for `return`. The `result` variable will be returned implicitly. |
Nim has a magic variable, `result`, which can be used as a substitute for `return`. The `result` variable will be returned implicitly. |
||
< |
<syntaxhighlight lang="nim">proc multiply(a, b: int): int = |
||
result = a * b</ |
result = a * b</syntaxhighlight> |
||
Here is the same function but with the use of the `return` keyword. |
Here is the same function but with the use of the `return` keyword. |
||
< |
<syntaxhighlight lang="nim">proc multiply(a, b: int): int = |
||
return a * b</ |
return a * b</syntaxhighlight> |
||
The last statement in a function implicitly is the result value: |
The last statement in a function implicitly is the result value: |
||
< |
<syntaxhighlight lang="nim">proc multiply(a, b: int): int = a * b</syntaxhighlight> |
||
=={{header|OASYS}}== |
=={{header|OASYS}}== |
||
< |
<syntaxhighlight lang="oasys_oac">method int multiply int x int y { |
||
return x * y |
return x * y |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OASYS Assembler}}== |
=={{header|OASYS Assembler}}== |
||
OASYS Assembler requires a prefix and suffix on names to indicate their types (an omitted suffix means a void type). |
OASYS Assembler requires a prefix and suffix on names to indicate their types (an omitted suffix means a void type). |
||
< |
<syntaxhighlight lang="oasys_oaa">[&MULTIPLY#,A#,B#],A#<,B#<MUL RF</syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
Oberon-2 uses procedures, and has a special procedure called a "Function Procedure" used to return a value. |
Oberon-2 uses procedures, and has a special procedure called a "Function Procedure" used to return a value. |
||
< |
<syntaxhighlight lang="oberon2">PROCEDURE Multiply(a, b: INTEGER): INTEGER; |
||
BEGIN |
BEGIN |
||
RETURN a * b; |
RETURN a * b; |
||
END Multiply;</ |
END Multiply;</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">function : Multiply(a : Float, b : Float) ~, Float { |
||
return a * b; |
return a * b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let int_multiply x y = x * y |
||
let float_multiply x y = x *. y</ |
let float_multiply x y = x *. y</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function r = mult(a, b) |
||
r = a .* b; |
r = a .* b; |
||
endfunction</ |
endfunction</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 2,327: | Line 2,785: | ||
If necessary, we can create a function with name multiply, but, it will just call * |
If necessary, we can create a function with name multiply, but, it will just call * |
||
<lang |
<syntaxhighlight lang="oforth">: multiply * ;</syntaxhighlight> |
||
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 : |
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 : |
||
< |
<syntaxhighlight lang="oforth">: multiply2(a, b) a b * ;</syntaxhighlight> |
||
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. |
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. |
||
Line 2,337: | Line 2,795: | ||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
Function creation implemented using keyword 'lambda'. This created anonymous function can be saved into local or global variable for further use. |
Function creation implemented using keyword 'lambda'. This created anonymous function can be saved into local or global variable for further use. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lambda (x y) |
(lambda (x y) |
||
(* x y)) |
(* x y)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Ol has two fully equal definitions of global named function (second one is syntactic sugar for first one). In fact both of them is saving the created lambda in global variable. |
Ol has two fully equal definitions of global named function (second one is syntactic sugar for first one). In fact both of them is saving the created lambda in global variable. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define multiply (lambda (x y) (* x y))) |
(define multiply (lambda (x y) (* x y))) |
||
(define (multiply x y) (* x y)) |
(define (multiply x y) (* x y)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
And only one definition of local named functions (with immediate calculation). This type of definition helps to implement local recursions. |
And only one definition of local named functions (with immediate calculation). This type of definition helps to implement local recursions. |
||
< |
<syntaxhighlight lang="scheme"> |
||
(let multiply ((x n) (y m)) |
(let multiply ((x n) (y m)) |
||
(* x y)) |
(* x y)) |
||
Line 2,363: | Line 2,821: | ||
(print (multiply 7 8)) |
(print (multiply 7 8)) |
||
; ==> 56 |
; ==> 56 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OOC}}== |
=={{header|OOC}}== |
||
< |
<syntaxhighlight lang="ooc"> |
||
multiply: func (a: Double, b: Double) -> Double { |
multiply: func (a: Double, b: Double) -> Double { |
||
a * b |
a * b |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
===Internal Procedure=== |
===Internal Procedure=== |
||
< |
<syntaxhighlight lang="rexx">SAY multiply(5, 6) |
||
EXIT |
EXIT |
||
multiply: |
multiply: |
||
PROCEDURE |
PROCEDURE |
||
PARSE ARG x, y |
PARSE ARG x, y |
||
RETURN x*y</ |
RETURN x*y</syntaxhighlight> |
||
===::Routine Directive=== |
===::Routine Directive=== |
||
< |
<syntaxhighlight lang="oorexx"> |
||
say multiply(5, 6) |
say multiply(5, 6) |
||
::routine multiply |
::routine multiply |
||
use arg x, y |
use arg x, y |
||
return x *y </ |
return x *y </syntaxhighlight> |
||
===Accomodate large factors=== |
===Accomodate large factors=== |
||
< |
<syntaxhighlight lang="oorexx">say multiply(123456789,987654321) |
||
say multiply_long(123456789,987654321) |
say multiply_long(123456789,987654321) |
||
::routine multiply |
::routine multiply |
||
Line 2,395: | Line 2,853: | ||
use arg x, y |
use arg x, y |
||
Numeric Digits (length(x)+length(y)) |
Numeric Digits (length(x)+length(y)) |
||
return x *y </ |
return x *y </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1.21932631E+17 |
<pre>1.21932631E+17 |
||
Line 2,401: | Line 2,859: | ||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
< |
<syntaxhighlight lang="progress (openedge abl)">function multiply returns dec (a as dec , b as dec ): |
||
return a * b . |
return a * b . |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">fun {Multiply X Y} |
||
X * Y |
X * Y |
||
end</ |
end</syntaxhighlight> |
||
Or by exploiting first-class functions: |
Or by exploiting first-class functions: |
||
< |
<syntaxhighlight lang="oz">Multiply = Number.'*'</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">multiply(a,b)=a*b;</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="parigp">multiply=(a,b)->a*b;</syntaxhighlight> |
||
Note that in both cases the <code>;</code> 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: |
Note that in both cases the <code>;</code> 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: |
||
< |
<syntaxhighlight lang="parigp">multiply={(a,b)->a*b;}</syntaxhighlight> |
||
which will return a function which calculates but does not return the product. |
which will return a function which calculates but does not return the product. |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
''see also: [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]]'' |
|||
(all versions and dialects) |
|||
<lang pascal>function multiply(a,b: real): real; |
|||
<syntaxhighlight lang="pascal">function multiply(a, b: real): real; |
|||
begin |
begin |
||
multiply := a * b |
|||
end;</ |
end;</syntaxhighlight> |
||
After a <tt>function</tt> has been activated, there must have be ''exactly one'' assignment to the (implicitly declared) variable bearing the same name as of the function. |
|||
Many processors do not comply with this specification, though, and allow ''overwriting'' the return value ''multiple'' times. |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
function multiply(a,b: real): real := a + b; |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
The most basic form: |
The most basic form: |
||
< |
<syntaxhighlight lang="perl">sub multiply { return $_[0] * $_[1] }</syntaxhighlight> |
||
or simply: |
or simply: |
||
< |
<syntaxhighlight lang="perl">sub multiply { $_[0] * $_[1] }</syntaxhighlight> |
||
Arguments in Perl subroutines are passed in the <code>@_</code> array, and they can be accessed directly, first one as <code>$_[0]</code>, second one as <code>$_[1]</code>, 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. |
Arguments in Perl subroutines are passed in the <code>@_</code> array, and they can be accessed directly, first one as <code>$_[0]</code>, second one as <code>$_[1]</code>, 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 [http://perldoc.perl.org/perlsub.html#Prototypes subroutine prototypes]: |
This is an example using [http://perldoc.perl.org/perlsub.html#Prototypes subroutine prototypes]: |
||
< |
<syntaxhighlight lang="perl">sub multiply( $$ ) |
||
{ |
{ |
||
my ($a, $b) = @_; |
my ($a, $b) = @_; |
||
return $a * $b; |
return $a * $b; |
||
}</ |
}</syntaxhighlight> |
||
The above subroutine can only be called with exactly two [http://perldoc.perl.org/perldata.html#Scalar-values scalar values] (two dollar signs in the signature) but those values may be not numbers or not even defined. The <code>@_</code> array is unpacked into <code>$a</code> and <code>$b</code> lexical variables, which are used later. |
The above subroutine can only be called with exactly two [http://perldoc.perl.org/perldata.html#Scalar-values scalar values] (two dollar signs in the signature) but those values may be not numbers or not even defined. The <code>@_</code> array is unpacked into <code>$a</code> and <code>$b</code> 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): |
The arguments can be automatically unpacked into lexical variables using the experimental signatures feature (in core as of 5.20): |
||
< |
<syntaxhighlight lang="perl">use experimental 'signatures'; |
||
sub multiply ($x, $y) { |
sub multiply ($x, $y) { |
||
return $x * $y; |
return $x * $y; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
{{libheader|Phix/basics}} |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">multiply</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">multiply</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span> |
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
<lang |
<syntaxhighlight lang="phixmonti">def multiply * enddef</syntaxhighlight> |
||
=={{header|PHL}}== |
=={{header|PHL}}== |
||
< |
<syntaxhighlight lang="phl">@Integer multiply(@Integer a, @Integer b) [ |
||
return a * b; |
return a * b; |
||
]</ |
]</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function multiply( $a, $b ) |
||
{ |
{ |
||
return $a * $b; |
return $a * $b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="php">multiply(A, B) = A*B. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de multiply (A B) |
||
(* A B) )</ |
(* A B) )</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">int multiply(int a, int b){ |
||
return a * b; |
return a * b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">PRODUCT: procedure (a, b) returns (float); |
||
declare (a, b) float; |
declare (a, b) float; |
||
return (a*b); |
return (a*b); |
||
end PRODUCT;</ |
end PRODUCT;</syntaxhighlight> |
||
=={{header|PL/SQL}}== |
=={{header|PL/SQL}}== |
||
< |
<syntaxhighlight lang="plsql">FUNCTION multiply(p_arg1 NUMBER, p_arg2 NUMBER) RETURN NUMBER |
||
IS |
IS |
||
v_product NUMBER; |
v_product NUMBER; |
||
Line 2,498: | Line 2,964: | ||
v_product := p_arg1 * p_arg2; |
v_product := p_arg1 * p_arg2; |
||
RETURN v_product; |
RETURN v_product; |
||
END;</ |
END;</syntaxhighlight> |
||
=={{header|Plain English}}== |
=={{header|Plain English}}== |
||
The <code>Multiply a number by another number</code> routine is already defined in the noodle, so we need to tweak the wording slightly so the compiler doesn't complain about redefinition (or so the definition isn't recursive). Note that <code>the number</code> refers to the parameter <code>a number</code> and <code>the other number</code> refers to the parameter <code>another number</code>. |
The <code>Multiply a number by another number</code> routine is already defined in the noodle, so we need to tweak the wording slightly so the compiler doesn't complain about redefinition (or so the definition isn't recursive). Note that <code>the number</code> refers to the parameter <code>a number</code> and <code>the other number</code> refers to the parameter <code>another number</code>. |
||
< |
<syntaxhighlight lang="plainenglish">To multiply a number with another number: |
||
Multiply the number by the other number.</ |
Multiply the number by the other number.</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">define multiply(a, b); |
||
a * b |
a * b |
||
enddefine;</ |
enddefine;</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
Inbuilt: |
Inbuilt: |
||
<lang |
<syntaxhighlight lang="postscript">3 4 mul</syntaxhighlight> |
||
Function would be: |
Function would be: |
||
< |
<syntaxhighlight lang="postscript">/multiply{ |
||
/x exch def |
/x exch def |
||
/y exch def |
/y exch def |
||
x y mul = |
x y mul = |
||
}def</ |
}def</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
The most basic variant of function definition would be the kind which uses positional parameters and therefore doesn't need to declare much: |
The most basic variant of function definition would be the kind which uses positional parameters and therefore doesn't need to declare much: |
||
< |
<syntaxhighlight lang="powershell">function multiply { |
||
return $args[0] * $args[1] |
return $args[0] * $args[1] |
||
}</ |
}</syntaxhighlight> |
||
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": |
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": |
||
< |
<syntaxhighlight lang="powershell">function multiply { |
||
$args[0] * $args[1] |
$args[0] * $args[1] |
||
}</ |
}</syntaxhighlight> |
||
Furthermore, the function arguments can be stated and named explicitly: |
Furthermore, the function arguments can be stated and named explicitly: |
||
< |
<syntaxhighlight lang="powershell">function multiply ($a, $b) { |
||
return $a * $b |
return $a * $b |
||
}</ |
}</syntaxhighlight> |
||
There is also an alternative style for declaring parameters. The choice is mostly a matter of personal preference: |
There is also an alternative style for declaring parameters. The choice is mostly a matter of personal preference: |
||
< |
<syntaxhighlight lang="powershell">function multiply { |
||
param ($a, $b) |
param ($a, $b) |
||
return $a * $b |
return $a * $b |
||
}</ |
}</syntaxhighlight> |
||
And the arguments can have an explicit type: |
And the arguments can have an explicit type: |
||
< |
<syntaxhighlight lang="powershell">function multiply ([int] $a, [int] $b) { |
||
return $a * $b |
return $a * $b |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
Processing is based on Java, and thus uses a familiar C-style syntax for function definition—as it does for much else. For the sake of argument, this implementation of <tt>multiply</tt> uses single-precision floats: other numeral types are available. |
Processing is based on Java, and thus uses a familiar C-style syntax for function definition—as it does for much else. For the sake of argument, this implementation of <tt>multiply</tt> uses single-precision floats: other numeral types are available. |
||
< |
<syntaxhighlight lang="java">float multiply(float x, float y) |
||
{ |
{ |
||
return x * y; |
return x * y; |
||
}</ |
}</syntaxhighlight> |
||
==={{header|Processing Python mode}}=== |
==={{header|Processing Python mode}}=== |
||
Processing Python mode is based on Jython, a fully implemented Python 2 interpreter, and thus uses familiar Python syntax for function definition-as it does for much else. |
Processing Python mode is based on Jython, a fully implemented Python 2 interpreter, and thus uses familiar Python syntax for function definition-as it does for much else. |
||
< |
<syntaxhighlight lang="python">def multiply(x, y): |
||
return x * y</ |
return x * y</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|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): |
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): |
||
< |
<syntaxhighlight lang="prolog">multiply(A, B, P) :- P is A * B.</syntaxhighlight> |
||
This is what it looks like in use: |
This is what it looks like in use: |
||
< |
<syntaxhighlight lang="prolog">go :- |
||
multiply(5, 2, P), |
multiply(5, 2, P), |
||
format("The product is ~d.~n", [P]).</ |
format("The product is ~d.~n", [P]).</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="prolog">test_multiply :- |
||
multiply(5, 2, 10), % this will pass |
multiply(5, 2, 10), % this will pass |
||
multiply(3, 4, 11). % this will not pass</ |
multiply(3, 4, 11). % this will not pass</syntaxhighlight> |
||
Still, the lack of user-defined functions remains an annoyance. |
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 [http://packs.ndrix.com/function_expansion/index.html function_expansion] pack (separately installed through the packs system) for SWI-Prolog. Similar code could be made in any Prolog implementation, however. |
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 [http://packs.ndrix.com/function_expansion/index.html function_expansion] pack (separately installed through the packs system) for SWI-Prolog. Similar code could be made in any Prolog implementation, however. |
||
< |
<syntaxhighlight lang="prolog">:- use_module(library(function_expansion)). |
||
user:function_expansion(multiply(A, B), P, P is A * B). % "function" definition |
user:function_expansion(multiply(A, B), P, P is A * B). % "function" definition |
||
go :- |
go :- |
||
format("The product is ~d.~n", [multiply(5, 2)]).</ |
format("The product is ~d.~n", [multiply(5, 2)]).</syntaxhighlight> |
||
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 <code>go/0</code> term into the following code: |
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 <code>go/0</code> term into the following code: |
||
< |
<syntaxhighlight lang="prolog">go :- |
||
A is 5*2, |
A is 5*2, |
||
format('The product is ~d.~n', [A]).</ |
format('The product is ~d.~n', [A]).</syntaxhighlight> |
||
=={{header|PureBasic}}== |
|||
<lang PureBasic>Procedure multiply(a,b) |
|||
ProcedureReturn a*b |
|||
EndProcedure</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
Function definition: |
Function definition: |
||
< |
<syntaxhighlight lang="python">def multiply(a, b): |
||
return a * b</ |
return a * b</syntaxhighlight> |
||
Lambda function definition: |
Lambda function definition: |
||
< |
<syntaxhighlight lang="python">multiply = lambda a, b: a * b</syntaxhighlight> |
||
A callable class definition allows functions and classes to use the same interface: |
A callable class definition allows functions and classes to use the same interface: |
||
< |
<syntaxhighlight lang="python">class Multiply: |
||
def __init__(self): |
def __init__(self): |
||
pass |
pass |
||
Line 2,601: | Line 3,062: | ||
multiply = Multiply() |
multiply = Multiply() |
||
print multiply(2, 4) # prints 8</ |
print multiply(2, 4) # prints 8</syntaxhighlight> |
||
(No extra functionality is shown in ''this'' class definition). |
(No extra functionality is shown in ''this'' class definition). |
||
=={{header|Q}}== |
=={{header|Q}}== |
||
< |
<syntaxhighlight lang="q">multiply:{[a;b] a*b}</syntaxhighlight> |
||
or |
or |
||
<lang |
<syntaxhighlight lang="q">multiply:{x*y}</syntaxhighlight> |
||
or |
or |
||
<lang |
<syntaxhighlight lang="q">multiply:*</syntaxhighlight> |
||
Using it |
Using it |
||
< |
<syntaxhighlight lang="q">multiply[2;3] |
||
6</ |
6</syntaxhighlight> |
||
=={{header|Quack}}== |
=={{header|Quack}}== |
||
You have several ways to define a function in Quack. You can do it by the classic way: |
You have several ways to define a function in Quack. You can do it by the classic way: |
||
< |
<syntaxhighlight lang="quack">fn multiply[ a; b ] |
||
^ a * b |
^ a * b |
||
end</ |
end</syntaxhighlight> |
||
Using lambda-expressions: |
Using lambda-expressions: |
||
< |
<syntaxhighlight lang="quack">let multiply :- fn { a; b | a * b }</syntaxhighlight> |
||
And using partial anonymous functions:< |
And using partial anonymous functions:<syntaxhighlight lang="quack">let multiply :- &(*)</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">[ * ] is multiply ( n n --> n )</syntaxhighlight> |
||
In the Quackery shell (REPL): |
In the Quackery shell (REPL): |
||
<pre> |
<pre> |
||
Line 2,640: | Line 3,101: | ||
Words don't have to be named. We could have written the above as: |
Words don't have to be named. We could have written the above as: |
||
< |
<syntaxhighlight lang="quackery">2 ' [ * ] 3 swap do</syntaxhighlight> |
||
By quoting the nest containing <code>*</code> with the <code>'</code> word, we have prevented it from being executed immediately and placed it on the data stack. Now it can be manipulated like any other nest or data stack object. We can use <code>do</code> to execute the contents of the nest. |
By quoting the nest containing <code>*</code> with the <code>'</code> word, we have prevented it from being executed immediately and placed it on the data stack. Now it can be manipulated like any other nest or data stack object. We can use <code>do</code> to execute the contents of the nest. |
||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="rsplus">mult <- function(a,b) a*b</syntaxhighlight> |
||
In general: |
In general: |
||
< |
<syntaxhighlight lang="rsplus">mult <- function(a,b) { |
||
a*b |
a*b |
||
# or: |
# or: |
||
# return(a*b) |
# return(a*b) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
A simple function definition that takes 2 arguments. |
A simple function definition that takes 2 arguments. |
||
< |
<syntaxhighlight lang="racket">(define (multiply a b) (* a b))</syntaxhighlight> |
||
Using an explicit <code>lambda</code> or <code>λ</code> is completely equivalent: |
Using an explicit <code>lambda</code> or <code>λ</code> is completely equivalent: |
||
< |
<syntaxhighlight lang="racket">(define multiply (lambda (a b) (* a b)))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="racket">(define multiply (λ (a b) (* a b)))</syntaxhighlight> |
||
Note that <code>*</code> is a function value, so the following code also works (although <code>multiply</code> will now be variadic function). |
Note that <code>*</code> is a function value, so the following code also works (although <code>multiply</code> will now be variadic function). |
||
<lang |
<syntaxhighlight lang="racket">(define multiply *)</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
Without a signature: |
Without a signature: |
||
<lang |
<syntaxhighlight lang="raku" line>sub multiply { return @_[0] * @_[1]; }</syntaxhighlight> |
||
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. |
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 <code>@_</code> or <code>%_</code> appear in the body.) In fact, we can define the variadic version explicitly, which still works for two arguments: |
(Beware that a subroutine without an explicit signature, like this one, magically becomes variadic (rather than nullary) only if <code>@_</code> or <code>%_</code> appear in the body.) In fact, we can define the variadic version explicitly, which still works for two arguments: |
||
<lang |
<syntaxhighlight lang="raku" line>sub multiply { [*] @_ }</syntaxhighlight> |
||
With formal parameters and a return type: |
With formal parameters and a return type: |
||
<lang |
<syntaxhighlight lang="raku" line>sub multiply (Rat $a, Rat $b --> Rat) { $a * $b }</syntaxhighlight> |
||
Same thing: |
Same thing: |
||
<lang |
<syntaxhighlight lang="raku" line>my Rat sub multiply (Rat $a, Rat $b) { $a * $b }</syntaxhighlight> |
||
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: |
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 |
<syntaxhighlight lang="raku" line>my &multiply := -> $a, $b { $a * $b };</syntaxhighlight> |
||
Another way to write a lambda is with internal placeholder parameters: |
Another way to write a lambda is with internal placeholder parameters: |
||
<lang |
<syntaxhighlight lang="raku" line>my &multiply := { $^a * $^b };</syntaxhighlight> |
||
(And, in fact, our original <tt>@_</tt> above is just a variadic self-declaring placeholder argument. And the famous Perl "topic", <tt>$_</tt>, is just a self-declared parameter to a unary block.) |
(And, in fact, our original <tt>@_</tt> above is just a variadic self-declaring placeholder argument. And the famous Perl "topic", <tt>$_</tt>, is just a self-declared parameter to a unary block.) |
||
You may also curry both built-in and user-defined operators by supplying a <tt>*</tt> (known as "whatever") in place of the argument that is <i>not</i> to be curried: |
You may also curry both built-in and user-defined operators by supplying a <tt>*</tt> (known as "whatever") in place of the argument that is <i>not</i> to be curried: |
||
<lang |
<syntaxhighlight lang="raku" line>my &multiply := * * *;</syntaxhighlight> |
||
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. |
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 |
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: |
curry a cascade of methods with only the original invocant missing: |
||
<lang |
<syntaxhighlight lang="raku" line>@list.grep( *.substr(0,1).lc.match(/<[0..9 a..f]>/) )</syntaxhighlight> |
||
This is equivalent to: |
This is equivalent to: |
||
<lang |
<syntaxhighlight lang="raku" line>@list.grep( -> $obj { $obj.substr(0,1).lc.match(/<[0..9 a..f]>/) } )</syntaxhighlight> |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">define multiply use a, b |
||
a b *</ |
a b *</syntaxhighlight> |
||
Or optional infix: |
Or optional infix: |
||
< |
<syntaxhighlight lang="raven">define multiply use a, b |
||
(a * b)</ |
(a * b)</syntaxhighlight> |
||
Or skip named vars: |
Or skip named vars: |
||
<lang |
<syntaxhighlight lang="raven">define multiply *</syntaxhighlight> |
||
=={{header|REALbasic}}== |
|||
<lang vb> |
|||
Function Multiply(a As Integer, b As Integer) As Integer |
|||
Return a * b |
|||
End Function |
|||
</lang> |
|||
=={{header|REBOL}}== |
=={{header|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: |
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: |
||
< |
<syntaxhighlight lang="rebol">multiply: func [a b][a * b]</syntaxhighlight> |
||
=={{header|Relation}}== |
=={{header|Relation}}== |
||
<syntaxhighlight lang="relation"> |
|||
<lang Relation> |
|||
function multiply(a,b) |
function multiply(a,b) |
||
set result = a*b |
set result = a*b |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">: multiply ( nn-n ) * ;</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===exactitudeness=== |
===exactitudeness=== |
||
< |
<syntaxhighlight lang="rexx">multiply: return arg(1) * arg(2) /*return the product of the two arguments.*/</syntaxhighlight> |
||
===cleaner display=== |
===cleaner display=== |
||
Line 2,730: | Line 3,184: | ||
<br><br>I.E.: ''' 3.0 * 4.00 ''' yields the product: '''12.000''' |
<br><br>I.E.: ''' 3.0 * 4.00 ''' yields the product: '''12.000''' |
||
<br><br>This version eliminates the '''.000''' from the product. |
<br><br>This version eliminates the '''.000''' from the product. |
||
< |
<syntaxhighlight lang="rexx">multiply: return arg(1) * arg(2) / 1 /*return with a normalized product of 2 args. */</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
func multiply x,y return x*y |
func multiply x,y return x*y |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|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: |
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: |
||
< |
<syntaxhighlight lang="rlab">>> class(sin) |
||
function |
function |
||
>> type(sin) |
>> type(sin) |
||
builtin</ |
builtin</syntaxhighlight> |
||
Functions are a data class on their own, or they can be member of a list (associative array). |
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 |
1. user function specified from built-in functions, here basic addition |
||
< |
<syntaxhighlight lang="rlab">f = function(x, y) |
||
{ |
{ |
||
return x + y; |
return x + y; |
||
Line 2,754: | Line 3,208: | ||
function |
function |
||
>> type(f) |
>> type(f) |
||
user</ |
user</syntaxhighlight> |
||
2. function can be member of a list (associative array) |
2. function can be member of a list (associative array) |
||
< |
<syntaxhighlight lang="rlab">somelist = <<>>; |
||
somelist.f = function(x, y) |
somelist.f = function(x, y) |
||
{ |
{ |
||
rval = x + y; |
rval = x + y; |
||
return rval; |
return rval; |
||
};</ |
};</syntaxhighlight> |
||
3. user function which uses a function that is specified as a member of some list, here we use ''somelist'' from above: |
3. user function which uses a function that is specified as a member of some list, here we use ''somelist'' from above: |
||
< |
<syntaxhighlight lang="rlab">g = function(x, y) |
||
{ |
{ |
||
global(somelist); |
global(somelist); |
||
rval = x * somelist.f(x, 2*y); |
rval = x * somelist.f(x, 2*y); |
||
return rval; |
return rval; |
||
};</ |
};</syntaxhighlight> |
||
=={{header|RPL}}== |
|||
≪ * ≫ 'MULT' STO |
|||
2 3 MULT |
|||
{{out}} |
|||
<pre>6</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def multiply(a, b) |
||
a * b |
a * b |
||
end</ |
end</syntaxhighlight> |
||
Ruby 3.0 adds endless method definition: |
|||
<syntaxhighlight lang="ruby">def multiply(a, b) = a * b</syntaxhighlight> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn multiply(a: i32, b: i32) -> i32 { |
||
a * b |
a * b |
||
}</ |
}</syntaxhighlight> |
||
=={{header|S-BASIC}}== |
|||
S-BASIC is unusual in that the function return value is assigned to the END statement that terminates the function. |
|||
<lang basic> |
|||
function multiply(a, b = real) = real |
|||
end = a * b |
|||
</lang> |
|||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
-- we cannot have "functions" (methods) outside classes |
-- we cannot have "functions" (methods) outside classes |
||
mult(a, b:FLT):FLT is return a*b; end; |
mult(a, b:FLT):FLT is return a*b; end; |
||
Line 2,797: | Line 3,251: | ||
#OUT + mult(5.2, 3.4) + "\n"; |
#OUT + mult(5.2, 3.4) + "\n"; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def multiply(a: Int, b: Int) = a * b</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
<lang |
<syntaxhighlight lang="scheme">(define multiply *)</syntaxhighlight> |
||
Alternately, |
Alternately, |
||
< |
<syntaxhighlight lang="scheme">(define (multiply a b) |
||
(* a b))</ |
(* a b))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">const func float: multiply (in float: a, in float: b) is |
||
return a * b;</ |
return a * b;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
< |
<syntaxhighlight lang="sensetalk">put multiply(3,7) as words |
||
to multiply num1, num2 |
to multiply num1, num2 |
||
return num1 * num2 |
return num1 * num2 |
||
end multiply |
end multiply |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,825: | Line 3,279: | ||
=={{header|SETL}}== |
=={{header|SETL}}== |
||
< |
<syntaxhighlight lang="setl">proc multiply( a, b ); |
||
return a * b; |
return a * b; |
||
end proc;</ |
end proc;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func multiply(a, b) { |
||
a * b; |
a * b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
Simula uses the term <tt>procedure</tt> for subroutines/methods whether they return a value or not. A procedure that does return a value is declared with a data type (e.g. <tt>integer procedure</tt>), whereas one that does not is declared simply as <tt>procedure</tt>. This program defines <tt>multiply</tt> as an integer procedure and illustrates its use. Note that the second argument provided to <tt>Outint</tt> gives the width of the integer to be printed. |
Simula uses the term <tt>procedure</tt> for subroutines/methods whether they return a value or not. A procedure that does return a value is declared with a data type (e.g. <tt>integer procedure</tt>), whereas one that does not is declared simply as <tt>procedure</tt>. This program defines <tt>multiply</tt> as an integer procedure and illustrates its use. Note that the second argument provided to <tt>Outint</tt> gives the width of the integer to be printed. |
||
< |
<syntaxhighlight lang="simula">BEGIN |
||
INTEGER PROCEDURE multiply(x, y); |
INTEGER PROCEDURE multiply(x, y); |
||
INTEGER x, y; |
INTEGER x, y; |
||
Line 2,844: | Line 3,298: | ||
Outint(multiply(7,8), 2); |
Outint(multiply(7,8), 2); |
||
Outimage |
Outimage |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">define: #multiply -> [| :a :b | a * b].</syntaxhighlight> |
||
or using a macro: |
or using a macro: |
||
< |
<syntaxhighlight lang="slate">define: #multiply -> #* `er.</syntaxhighlight> |
||
The block may also be installed as a method like so: |
The block may also be installed as a method like so: |
||
< |
<syntaxhighlight lang="slate">a@(Number traits) multiplyBy: b@(Number traits) [a * b].</syntaxhighlight> |
||
or more explicitly (without sugar): |
or more explicitly (without sugar): |
||
< |
<syntaxhighlight lang="slate">[| :a :b | a * b] asMethod: #multipleBy: on: {Number traits. Number traits}.</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">|mul| |
||
mul := [ :a :b | a * b ].</ |
mul := [ :a :b | a * b ].</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol4"> define('multiply(a,b)') :(mul_end) |
||
multiply multiply = a * b :(return) |
multiply multiply = a * b :(return) |
||
mul_end |
mul_end |
||
Line 2,866: | Line 3,320: | ||
output = multiply(10.1,12.2) |
output = multiply(10.1,12.2) |
||
output = multiply(10,12) |
output = multiply(10,12) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
123.22 |
123.22 |
||
Line 2,873: | Line 3,327: | ||
=={{header|SNUSP}}== |
=={{header|SNUSP}}== |
||
For expediency, the function is adding three values, instead of multiplying two values. Another function, atoi (+48) is called before printing the result. |
For expediency, the function is adding three values, instead of multiplying two values. Another function, atoi (+48) is called before printing the result. |
||
< |
<syntaxhighlight lang="snusp">+1>++2=@\=>+++3=@\==@\=.=# prints '6' |
||
| | \=itoa=@@@+@+++++# |
| | \=itoa=@@@+@+++++# |
||
\=======!\==!/===?\<# |
\=======!\==!/===?\<# |
||
\>+<-/</ |
\>+<-/</syntaxhighlight> |
||
=={{header|SPARK}}== |
=={{header|SPARK}}== |
||
The function definition (multiplies two standard Integer): |
The function definition (multiplies two standard Integer): |
||
< |
<syntaxhighlight lang="ada">package Functions is |
||
function Multiply (A, B : Integer) return Integer; |
function Multiply (A, B : Integer) return Integer; |
||
--# pre A * B in Integer; -- See note below |
--# pre A * B in Integer; -- See note below |
||
--# return A * B; -- Implies commutativity on Multiply arguments |
--# return A * B; -- Implies commutativity on Multiply arguments |
||
end Functions;</ |
end Functions;</syntaxhighlight> |
||
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 : |
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 : |
||
< |
<syntaxhighlight lang="ada">type Input_Type is range 0 .. 10; |
||
type Result_Type is range 0 .. 100;</ |
type Result_Type is range 0 .. 100;</syntaxhighlight> |
||
and had a version of Multiply using these types. On the other hand, if arguments of Multiply are constants, this is provable straight away. |
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: |
The Multiply's implementation: |
||
< |
<syntaxhighlight lang="ada">package body Functions is |
||
function Multiply (A, B : Integer) return Integer is |
function Multiply (A, B : Integer) return Integer is |
||
begin |
begin |
||
return A * B; |
return A * B; |
||
end Multiply; |
end Multiply; |
||
end Functions;</ |
end Functions;</syntaxhighlight> |
||
=={{header|SPL}}== |
=={{header|SPL}}== |
||
Single-line function definition: |
Single-line function definition: |
||
< |
<syntaxhighlight lang="spl">multiply(a,b) <= a*b</syntaxhighlight> |
||
Multi-line function definition: |
Multi-line function definition: |
||
< |
<syntaxhighlight lang="spl">multiply(a,b)= |
||
x = a*b |
x = a*b |
||
<= x |
<= x |
||
.</ |
.</syntaxhighlight> |
||
=={{header|SSEM}}== |
=={{header|SSEM}}== |
||
Line 2,911: | Line 3,365: | ||
In this example, the main routine does nothing at all beyond calling the subroutine and halting after it has returned. The values <tt>A</tt> and <tt>B</tt> are passed in the two addresses located immediately before the subroutine begins; their product is returned in the address that formerly stored <tt>A</tt>. Given that the <tt>multiply</tt> subroutine begins at address 8, the calling routine looks like this: |
In this example, the main routine does nothing at all beyond calling the subroutine and halting after it has returned. The values <tt>A</tt> and <tt>B</tt> are passed in the two addresses located immediately before the subroutine begins; their product is returned in the address that formerly stored <tt>A</tt>. Given that the <tt>multiply</tt> subroutine begins at address 8, the calling routine looks like this: |
||
< |
<syntaxhighlight lang="ssem">01000000000000100000000000000000 0. -2 to c |
||
00100000000000000000000000000000 1. 4 to CI |
00100000000000000000000000000000 1. 4 to CI |
||
01111111111111111111111111111111 2. -2 |
01111111111111111111111111111111 2. -2 |
||
00000000000001110000000000000000 3. Stop |
00000000000001110000000000000000 3. Stop |
||
11100000000000000000000000000000 4. 7</ |
11100000000000000000000000000000 4. 7</syntaxhighlight> |
||
or in pseudocode: |
or in pseudocode: |
||
<pre> load &here |
<pre> load &here |
||
Line 2,921: | Line 3,375: | ||
here: halt</pre> |
here: halt</pre> |
||
Implementing <tt>multiply</tt> on the SSEM requires the use of repeated negation and subtraction. For the sake of example, the values 8 and 7 are provided for <tt>A</tt> and <tt>B</tt>. |
Implementing <tt>multiply</tt> on the SSEM requires the use of repeated negation and subtraction. For the sake of example, the values 8 and 7 are provided for <tt>A</tt> and <tt>B</tt>. |
||
< |
<syntaxhighlight lang="ssem">00010000000000000000000000000000 6. 8 |
||
11100000000000000000000000000000 7. 7 |
11100000000000000000000000000000 7. 7 |
||
11111000000001100000000000000000 8. c to 31 |
11111000000001100000000000000000 8. c to 31 |
||
Line 2,946: | Line 3,400: | ||
00110000000000000000000000000000 29. 12 |
00110000000000000000000000000000 29. 12 |
||
00000000000000000000000000000000 30. 0 |
00000000000000000000000000000000 30. 0 |
||
00000000000000000000000000000000 31. 0</ |
00000000000000000000000000000000 31. 0</syntaxhighlight> |
||
The pseudocode equivalent clarifies how the subroutine works, or how it would work on an architecture that supported <tt>load</tt> and <tt>add</tt>: |
The pseudocode equivalent clarifies how the subroutine works, or how it would work on an architecture that supported <tt>load</tt> and <tt>add</tt>: |
||
<pre>a: equals #8 |
<pre>a: equals #8 |
||
Line 2,967: | Line 3,421: | ||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="ocaml">val multiply = op *</syntaxhighlight> |
||
Equivalently, |
Equivalently, |
||
< |
<syntaxhighlight lang="ocaml">fun multiply (x, y) = x * y</syntaxhighlight> |
||
Using lambda syntax: |
Using lambda syntax: |
||
< |
<syntaxhighlight lang="sml">val multiply = fn (x, y) => x * y</syntaxhighlight> |
||
Curried form: |
Curried form: |
||
< |
<syntaxhighlight lang="ocaml">fun multiply x y = x * y</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
Line 2,980: | Line 3,434: | ||
Stata's macro language does not have functions, but commands. Output is usually saved as a "stored result" (but could also be saved in a global macro variable, in a scalar or matrix, in a dataset or simply printed to the Results window). See '''[https://www.stata.com/help.cgi?program program]''' and '''[https://www.stata.com/help.cgi?return]''' in Stata documentation. |
Stata's macro language does not have functions, but commands. Output is usually saved as a "stored result" (but could also be saved in a global macro variable, in a scalar or matrix, in a dataset or simply printed to the Results window). See '''[https://www.stata.com/help.cgi?program program]''' and '''[https://www.stata.com/help.cgi?return]''' in Stata documentation. |
||
< |
<syntaxhighlight lang="stata">prog def multiply, return |
||
args a b |
args a b |
||
return sca product=`a'*`b' |
return sca product=`a'*`b' |
||
Line 2,986: | Line 3,440: | ||
multiply 77 13 |
multiply 77 13 |
||
di r(product)</ |
di r(product)</syntaxhighlight> |
||
'''Output''' |
'''Output''' |
||
Line 2,995: | Line 3,449: | ||
Mata is the matrix language of Stata. Here is how to define a function |
Mata is the matrix language of Stata. Here is how to define a function |
||
< |
<syntaxhighlight lang="stata">mata |
||
scalar multiply(scalar x, scalar y) { |
scalar multiply(scalar x, scalar y) { |
||
return(x*y) |
return(x*y) |
||
Line 3,001: | Line 3,455: | ||
multiply(77,13) |
multiply(77,13) |
||
end</ |
end</syntaxhighlight> |
||
'''Output''' |
'''Output''' |
||
Line 3,008: | Line 3,462: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func multiply(a: Double, b: Double) -> Double { |
||
return a * b |
return a * b |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Symstatic}}== |
|||
You can write functions in let expressions or anonimously: |
|||
<syntaxhighlight lang="symstatic">let prod(a, b) := a*b |
|||
let prodAnon := (a, b) -> a*b |
|||
assert(prodAnon(2, 2) = ((a, b) -> a*b)(2, 2)) |
|||
assert(prod(2, 2) = prodAnon(2, 2)) |
|||
</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Strictly as described in the task: |
Strictly as described in the task: |
||
< |
<syntaxhighlight lang="tcl">proc multiply { arg1 arg2 } { |
||
return [expr {$arg1 * $arg2}] |
return [expr {$arg1 * $arg2}] |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
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): |
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): |
||
< |
<syntaxhighlight lang="tcl">proc tcl::mathfunc::multiply {arg1 arg2} { |
||
return [expr {$arg1 * $arg2}] |
return [expr {$arg1 * $arg2}] |
||
} |
} |
||
Line 3,026: | Line 3,489: | ||
if {multiply(6, 9) == 42} { |
if {multiply(6, 9) == 42} { |
||
puts "Welcome, Citizens of Golgafrincham from the B-Ark!" |
puts "Welcome, Citizens of Golgafrincham from the B-Ark!" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TI-89 BASIC}}== |
|||
<lang ti89b>multiply(a, b) |
|||
Func |
|||
Return a * b |
|||
EndFunc</lang> |
|||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
< |
<syntaxhighlight lang="toka">[ ( ab-c ) * ] is multiply</syntaxhighlight> |
||
=={{header|Transd}}== |
=={{header|Transd}}== |
||
< |
<syntaxhighlight lang="scheme">multiply: (lambda a Double() b Double() (* a b))</syntaxhighlight> |
||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 3,044: | Line 3,501: | ||
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: <code>@(* a b)</code> |
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: <code>@(* a b)</code> |
||
< |
<syntaxhighlight lang="txr">@(define multiply (a b out)) |
||
@(bind out @(* a b)) |
@(bind out @(* a b)) |
||
@(end) |
@(end) |
||
@(multiply 3 4 result)</ |
@(multiply 3 4 result)</syntaxhighlight> |
||
<pre>$ txr -B multiply.txr |
<pre>$ txr -B multiply.txr |
||
result="12"</pre> |
result="12"</pre> |
||
In the embedded Lisp dialect, it is possible to write an ordinary function that returns a value: |
In the embedded Lisp dialect, it is possible to write an ordinary function that returns a value: |
||
< |
<syntaxhighlight lang="txrlisp">(defun mult (a b) (* a b)) |
||
(put-line `3 * 4 = @(mult 3 4)`)</ |
(put-line `3 * 4 = @(mult 3 4)`)</syntaxhighlight> |
||
<pre>$ txr multiply.tl |
<pre>$ txr multiply.tl |
||
3 * 4 = 12</pre> |
3 * 4 = 12</pre> |
||
=={{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|UNIX Shell}}== |
=={{header|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. |
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. |
||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="bash">multiply() { |
||
# There is never anything between the parentheses after the function name |
# There is never anything between the parentheses after the function name |
||
# Arguments are obtained using the positional parameters $1, and $2 |
# Arguments are obtained using the positional parameters $1, and $2 |
||
Line 3,076: | Line 3,525: | ||
# Call the function |
# Call the function |
||
multiply 3 4 # The function is invoked in statement context |
multiply 3 4 # The function is invoked in statement context |
||
echo $? # The dollarhook special variable gives the return value</ |
echo $? # The dollarhook special variable gives the return value</syntaxhighlight> |
||
{{works with|Bash}} |
{{works with|Bash}} |
||
return an exit code |
return an exit code |
||
< |
<syntaxhighlight lang="bash">multiply() { |
||
return $(($1 * $2)) |
return $(($1 * $2)) |
||
} |
} |
||
multiply 5 6 |
multiply 5 6 |
||
echo $?</ |
echo $?</syntaxhighlight> |
||
echo the result |
echo the result |
||
< |
<syntaxhighlight lang="bash">multiply() { |
||
echo -n $(($1 * $2)) |
echo -n $(($1 * $2)) |
||
} |
} |
||
echo $(multiply 5 6)</ |
echo $(multiply 5 6)</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa"># multiply is a built-in in ursa, so the function is called mult instead |
||
def mult (int a, int b) |
def mult (int a, int b) |
||
return (* a b) |
return (* a b) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 3,102: | Line 3,551: | ||
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 <code>math..mul</code>. |
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 <code>math..mul</code>. |
||
This is the definition in point free form, |
This is the definition in point free form, |
||
< |
<syntaxhighlight lang="ursala">multiply = math..mul</syntaxhighlight> |
||
this is the definition using lambda abstraction |
this is the definition using lambda abstraction |
||
< |
<syntaxhighlight lang="ursala">multiply = ("a","b"). math..mul ("a","b")</syntaxhighlight> |
||
and this is the definition using pattern matching. |
and this is the definition using pattern matching. |
||
< |
<syntaxhighlight lang="ursala">multiply("a","b") = math..mul ("a","b")</syntaxhighlight> |
||
=={{header|V}}== |
=={{header|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. |
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 |
<syntaxhighlight lang="v">[multiply *].</syntaxhighlight> |
||
Using it |
Using it |
||
< |
<syntaxhighlight lang="v">2 3 multiply |
||
=6</ |
=6</syntaxhighlight> |
||
V also allows internal bindings. |
V also allows internal bindings. |
||
< |
<syntaxhighlight lang="v">[multiply |
||
[a b] let |
[a b] let |
||
a b *].</ |
a b *].</syntaxhighlight> |
||
=={{header| |
=={{header|V (Vlang)}}== |
||
<syntaxhighlight lang="Zig"> |
|||
<lang vb>Function Multiply(lngMcand As Long, lngMplier As Long) As Long |
|||
fn multiply(a f64, b f64) f64 { |
|||
Multiply = lngMcand * lngMplier |
|||
return a * b |
|||
End Function</lang> |
|||
} |
|||
To use this function : |
|||
<lang vb>Sub Main() |
|||
Dim Result As Long |
|||
Result = Multiply(564231, 897) |
|||
End Sub</lang> |
|||
fn main() { |
|||
=={{header|VBScript}}== |
|||
print(multiply(5, 6)) |
|||
} |
|||
multiply = multiplicand * multiplier |
|||
</syntaxhighlight> |
|||
end function</lang> |
|||
Usage: |
|||
<lang vb>dim twosquared |
|||
twosquared = multiply(2, 2)</lang> |
|||
{{out}} |
|||
=={{header|Visual Basic}}== |
|||
<pre> |
|||
{{works with|Visual Basic|VB6 Standard}} |
|||
30.0 |
|||
<lang vb> |
|||
</pre> |
|||
Function multiply(a As Integer, b As Integer) As Integer |
|||
multiply = a * b |
|||
End Function |
|||
</lang> |
|||
Call the function |
|||
<lang vb>Multiply(6, 111)</lang> |
|||
=={{header|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> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
A straightforward way to say how calls of the form <code>(multiply a b)</code> are translated: |
A straightforward way to say how calls of the form <code>(multiply a b)</code> are translated: |
||
< |
<syntaxhighlight lang="python">def (multiply a b) |
||
a*b</ |
a*b</syntaxhighlight> |
||
< |
<syntaxhighlight lang="python">(multiply 3 4) |
||
=> 12</ |
=> 12</syntaxhighlight> |
||
Functions can also use keyword args. |
Functions can also use keyword args. |
||
< |
<syntaxhighlight lang="python">(multiply 3 :a 4) # arg order doesn't matter here, but try subtract instead |
||
=> 12</ |
=> 12</syntaxhighlight> |
||
Finally, we can give parameters better keyword args using <em>aliases</em>: |
Finally, we can give parameters better keyword args using <em>aliases</em>: |
||
< |
<syntaxhighlight lang="python">def (multiply a b|by) |
||
(* a b)</ |
(* a b)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="python">multiply 3 :by 4 |
||
=> 12</ |
=> 12</syntaxhighlight> |
||
=={{header|WebAssembly}}== |
=={{header|WebAssembly}}== |
||
Line 3,186: | Line 3,616: | ||
The following 'multiply' function will work for any type(s) that support the '*' operator. |
The following 'multiply' function will work for any type(s) that support the '*' operator. |
||
However, it will produce a runtime error otherwise, as demonstrated by the final example. |
However, it will produce a runtime error otherwise, as demonstrated by the final example. |
||
< |
<syntaxhighlight lang="wren">var multiply = Fn.new { |a, b| a * b } |
||
System.print(multiply.call(3, 7)) |
System.print(multiply.call(3, 7)) |
||
System.print(multiply.call("abc", 3)) |
System.print(multiply.call("abc", 3)) |
||
System.print(multiply.call([1], 5)) |
System.print(multiply.call([1], 5)) |
||
System.print(multiply.call(true, false))</ |
System.print(multiply.call(true, false))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,217: | Line 3,647: | ||
The following is Unix-style "as" assembler syntax (including GNU as). The resulting function can be called from C with <code>multiply(123,456)</code>. |
The following is Unix-style "as" assembler syntax (including GNU as). The resulting function can be called from C with <code>multiply(123,456)</code>. |
||
< |
<syntaxhighlight lang="asm"> .text |
||
.globl multiply |
.globl multiply |
||
.type multiply,@function |
.type multiply,@function |
||
Line 3,223: | Line 3,653: | ||
movl 4(%esp), %eax |
movl 4(%esp), %eax |
||
mull 8(%esp) |
mull 8(%esp) |
||
ret</ |
ret</syntaxhighlight> |
||
The <code>.type</code> 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 <code>.size</code> directive only 4 bytes will be copied.) |
The <code>.type</code> 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 <code>.size</code> directive only 4 bytes will be copied.) |
||
Line 3,229: | Line 3,659: | ||
===NASM=== |
===NASM=== |
||
{{works with|NASM}} |
{{works with|NASM}} |
||
< |
<syntaxhighlight lang="asm">section .text |
||
global _start |
global _start |
||
Line 3,252: | Line 3,682: | ||
push 6 |
push 6 |
||
push 16 |
push 16 |
||
call _multiply_stack</ |
call _multiply_stack</syntaxhighlight> |
||
===MASM=== |
===MASM=== |
||
However, in MASM we do have function statements due to the preprocessor. |
However, in MASM we do have function statements due to the preprocessor. |
||
{{works with|MASM}} |
{{works with|MASM}} |
||
< |
<syntaxhighlight lang="asm">multiply proc arg1:dword, arg2:dword |
||
mov eax, arg1 |
mov eax, arg1 |
||
mov ebx, arg2 |
mov ebx, arg2 |
||
Line 3,263: | Line 3,693: | ||
mov eax, ebx |
mov eax, ebx |
||
ret |
ret |
||
multiply endp</ |
multiply endp</syntaxhighlight> |
||
Then to call it. |
Then to call it. |
||
< |
<syntaxhighlight lang="asm">invoke multiply, 6, 16 |
||
;or.. |
;or.. |
||
push 16 |
push 16 |
||
push 6 |
push 6 |
||
call multiply</ |
call multiply</syntaxhighlight> |
||
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|XBS}}== |
=={{header|XBS}}== |
||
Functions are defined by using the '''func''' keyword. |
Functions are defined by using the '''func''' keyword. |
||
< |
<syntaxhighlight lang="xbs">func multiply(a,b){ |
||
send a*b; |
send a*b; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
Functions can be defined using either 'classic' Lisp syntax: |
Functions can be defined using either 'classic' Lisp syntax: |
||
< |
<syntaxhighlight lang="lisp">(defun multiply (x y) |
||
(* x y))</ |
(* x y))</syntaxhighlight> |
||
or Scheme-style syntax: |
or Scheme-style syntax: |
||
< |
<syntaxhighlight lang="scheme">(define (multiply x y) |
||
(* x y))</ |
(* x y))</syntaxhighlight> |
||
or, if you prefer, with <tt>LAMBDA</tt>: |
or, if you prefer, with <tt>LAMBDA</tt>: |
||
< |
<syntaxhighlight lang="scheme">(define multiply |
||
(lambda (x y) (* x y)))</ |
(lambda (x y) (* x y)))</syntaxhighlight> |
||
=={{header|Xojo}}== |
|||
<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>Dim I As Integer = Multiply(7, 6)</lang> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight 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 |
int A, B; \the arguments are actually declared here, as integers |
||
return A*B; \the default (undeclared) function type is integer |
return A*B; \the default (undeclared) function type is integer |
||
Line 3,304: | Line 3,727: | ||
func real FloatMul(A, B); \floating point version |
func real FloatMul(A, B); \floating point version |
||
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;</ |
return A*B;</syntaxhighlight> |
||
=={{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). |
||
< |
<syntaxhighlight lang="xslt"><xsl:template name="multiply"> |
||
<xsl:param name="a" select="2"/> |
<xsl:param name="a" select="2"/> |
||
<xsl:param name="b" select="3"/> |
<xsl:param name="b" select="3"/> |
||
<xsl:value-of select="$a * $b"/> |
<xsl:value-of select="$a * $b"/> |
||
</xsl:template></ |
</xsl:template></syntaxhighlight> |
||
Usage examples. |
Usage examples. |
||
< |
<syntaxhighlight lang="xslt"><xsl:call-template name="multiply"> |
||
<xsl:with-param name="a">4</xsl:with-param> |
<xsl:with-param name="a">4</xsl:with-param> |
||
<xsl:with-param name="b">5</xsl:with-param> |
<xsl:with-param name="b">5</xsl:with-param> |
||
</xsl:call-template> |
</xsl:call-template> |
||
<xsl:call-template name="multiply"/> <-- using default parameters of 2 and 3 --></ |
<xsl:call-template name="multiply"/> <-- using default parameters of 2 and 3 --></syntaxhighlight> |
||
Available in XSLT 2.0 and later versions. |
Available in XSLT 2.0 and later versions. |
||
< |
<syntaxhighlight lang="xslt"><xsl:function name="mf:multiply"> |
||
<xsl:param name="a"/> |
<xsl:param name="a"/> |
||
<xsl:param name="b"/> |
<xsl:param name="b"/> |
||
<xsl:value-of select="$a * $b"/> |
<xsl:value-of select="$a * $b"/> |
||
</xsl:function></ |
</xsl:function></syntaxhighlight> |
||
Usage examples. |
Usage examples. |
||
< |
<syntaxhighlight lang="xslt">{mf:multiply(2,3)} |
||
<xsl:value-of select="mf:multiply(2,3)" /></ |
<xsl:value-of select="mf:multiply(2,3)" /></syntaxhighlight> |
||
=={{header|YAMLScript}}== |
|||
<syntaxhighlight lang="yaml"> |
|||
!yamlscript/v0 |
|||
# Main function definition with variable arguments: |
|||
defn main(& args): |
|||
answer =: |
|||
multiply: ARGS* |
|||
say: "multiply($(ARGS.join(', '))) = $answer" |
|||
# A multi-arity function definition: |
|||
defn multiply: |
|||
(): 1 |
|||
(x): x |
|||
(x y): x * y |
|||
(x y & more): |
|||
reduce multiply: multiply(x y) more |
|||
</syntaxhighlight> |
|||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">func multiply(x, y) { |
||
return x * y; |
return x * y; |
||
}</ |
}</syntaxhighlight> |
||
Example of interactive usage: |
Example of interactive usage: |
||
<pre>> multiply(2, 4.5) |
<pre>> multiply(2, 4.5) |
||
Line 3,342: | Line 3,784: | ||
A function's return values are whatever registers or memory are changed by the function. A good programmer will explain what is returned where by using comments. |
A function's return values are whatever registers or memory are changed by the function. A good programmer will explain what is returned where by using comments. |
||
< |
<syntaxhighlight lang="z80">doMultiply: |
||
;returns HL = HL times A. No overflow protection. |
;returns HL = HL times A. No overflow protection. |
||
push bc |
push bc |
||
Line 3,368: | Line 3,810: | ||
pop de |
pop de |
||
pop bc |
pop bc |
||
ret</ |
ret</syntaxhighlight> |
||
=={{header| |
=={{header|zig}}== |
||
< |
<syntaxhighlight lang="zig">fun multiply(x: i64, y: i64) i64 { |
||
return x * y; |
|||
<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> |
|||
//example call |
|||
=={{header|ZX Spectrum Basic}}== |
|||
const x: i64 = 4; |
|||
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 |
|||
const y: i64 = 23; |
|||
<lang zxbasic>10 PRINT FN m(3,4): REM call our function to produce a value of 12 |
|||
_ = multipy(x, y); // --> 93</syntaxhighlight> |
|||
20 STOP |
|||
9950 DEF FN m(a,b)=a*b</lang> |
|||
=={{header|zkl}}== |
|||
<syntaxhighlight lang="zkl">fcn multiply(x,y){x*y}</syntaxhighlight> |
|||
<syntaxhighlight lang="zkl">fcn(x,y){x*y}(4.5,3) // --> 13.5</syntaxhighlight> |
|||
Since all functions are vararg:<syntaxhighlight lang="zkl">fcn multiply{vm.arglist.reduce('*)} |
|||
multiply(1,2,3,4,5) //--> 120</syntaxhighlight> |
|||
Operators are first class objects so:<syntaxhighlight lang="zkl">var mul=Op("*"); mul(4,5) //-->20</syntaxhighlight> |
|||
{{omit from|GUISS}} |
{{omit from|GUISS}} |
Latest revision as of 19:51, 8 August 2024
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.
- Task
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).
- Related task
11l
Function definition:
F multiply(a, b)
R a * b
Lambda function definition:
V multiply = (a, b) -> a * b
360 Assembly
Linkage conventions are: register 1 : the parameter list, register 0 : the return value, and register 14 : the return address.
DEFFUN CSECT
USING DEFFUN,R13
SAVEAREA B PROLOG-SAVEAREA(R15)
DC 17F'0'
PROLOG STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 set base register
BEGIN L R2,=F'13'
ST R2,X X=13
L R2,=F'17'
ST R2,Y Y=17
LA R1,PARMLIST R1->PARMLIST
B SKIPPARM
PARMLIST DS 0F
DC A(X)
DC A(Y)
SKIPPARM BAL R14,MULTPLIC call MULTPLIC
ST R0,Z Z=MULTPLIC(X,Y)
RETURN L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15 set return code
BR R14 return to caller
*
MULTPLIC EQU * function MULTPLIC(X,Y)
L R2,0(R1) R2=(A(X),A(Y))
XR R4,R4 R4=0
L R5,0(R2) R5=X
L R6,4(R2) R6=Y
MR R4,R6 R4R5=R4R5*R6
LR R0,R5 R0=X*Y (R0 return value)
BR R14 end function MULTPLIC
*
X DS F
Y DS F
Z DS F
YREGS
END DEFFUN
6502 Assembly
As with other low-level languages, 6502 assembler has subroutines rather than functions in the strict sense. This implementation of MULTIPLY behaves rather like a function, however: it expects two 'parameters' to be passed in the index registers X and Y and it returns the answer in the accumulator. Note that the 6502 has no MUL instruction, so multiplication is carried out by repeated addition.
MULTIPLY: STX MULN ; 6502 has no "acc += xreg" instruction,
TXA ; so use a memory address
MULLOOP: DEY
CLC ; remember to clear the carry flag before
ADC MULN ; doing addition or subtraction
CPY #$01
BNE MULLOOP
RTS
An alternative implementation that multiplies A by X and checks if A/X is zero.
; https://skilldrick.github.io/easy6502/
; Multiplies A by X
define memory 1040
JMP MAIN
MULTIPLY: STA memory ; memory = A
BEQ MUL_END ; A = 0
TXA ; A = X
BEQ MUL_END ; X = 0 -> A = 0
LDA memory
CLC
MUL_LOOP: DEX ; X -= 1
BEQ MUL_END ; X = 0 -> A = A * X
ADC memory ; A += memory
JMP MUL_LOOP
MUL_END: RTS
MAIN: LDA #50
LDX #5
JSR MULTIPLY
68000 Assembly
What values are returned (if any) and where they are returned, will depend on the calling convention used. Code written by a C compiler will typically pass parameters onto the stack and use a "frame pointer" to reference them. For this simple example, the operands will be passed into the function using the registers D0
and D1
, and the output will be in D0
. A function is called by using JSR foo
where foo
is a labeled section of code or a 24-bit memory address. Execution will continue along starting at that address, until an RTS
is encountered, at which point the return address will be popped off the stack into the program counter.
MOVE.L D0,#$0200
MOVE.L D1,#$0400
JSR doMultiply
;rest of program
JMP $ ;halt
;;;;; somewhere far away from the code above
doMultiply:
MULU D0,D1
RTS
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.
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
8086 Assembly
A function is nothing more than a named section of code. A CALL
instruction will push the current value of the instruction pointer and then set the instruction pointer to that address. Execution will continue forward until a RET
statement is encountered, at which point the top of the stack is popped into the instruction pointer register. Note that the RET
statement assumes that the top of the stack contains the actual return address, even though in reality this may not be the case. There is no validation that the return address is correct! This is why it's important for the assembly programmer to ensure the stack is balanced at all times, otherwise your program will go running off to who knows where.
It's important to remember that, unlike other languages, execution of assembly code (and this is true for all assembly languages, not just the 8086) is on a purely linear path by default, much like in other "primitive" languages like BASIC, and so there is nothing stopping the instruction pointer from "falling into" subroutines. Often this can be handy if you're trying to code a variation on a function whose only difference is doing a few extra things at the beginning, but it's something you'll need to guard against, either with a return to the operating system or an infinite loop.
start:
mov al, 0x04
mov bl, 0x05
call multiply
;at this point in execution, the AX register contains 0x0900.
;more code goes here, ideally with some sort of guard against "fallthrough" into multiply.
; somewhere far away from start
multiply:
mul bl ;outputs 0x0014 to ax
ret
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program functMul64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/***********************/
/* Initialized data */
/***********************/
.data
szRetourLigne: .asciz "\n"
szMessResult: .asciz "Resultat : @ \n" // message result
/***********************
/* No Initialized data */
/***********************/
.bss
sZoneConv: .skip 24
.text
.global main
main:
// function multiply
mov x0,8
mov x1,50
bl multiply // call function
ldr x1,qAdrsZoneConv
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
mov x0,0 // return code
100: // end of program
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* Function multiply */
/******************************************************************/
/* x0 contains value 1 */
/* x1 contains value 2 */
/* x0 return résult */
multiply:
mul x0,x1,x0
ret // return function
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
ACL2
(defun multiply (a b) (* a b))
ActionScript
function multiply(a:Number, b:Number):Number {
return a * b;
}
Ada
function Multiply (A, B : Float) return Float;
and an implementation of:
function Multiply (A, B : Float) return Float is
begin
return A * B;
end Multiply;
The Ada 2012 standard provides an even simpler way to define and implement functions:
function Multiply(A, B: Float) return Float is (A * B);
Ada supports generic functions which can take generic formal parameters like the numeric type to use:
generic
type Number is digits <>;
function Multiply (A, B : Number) return Number;
implemented as:
function Multiply (A, B : Number) return Number is
begin
return A * B;
end Multiply;
To use this, you need to instantiate the function for each type e.g.
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);
Aime
real
multiply(real a, real b)
{
return a * b;
}
ALGOL 60
begin comment Function definition; integer procedure multiply(a,b); integer a,b; begin multiply:=a*b; end; integer c; c:=multiply(2,2); outinteger(1,c) end
- Output:
4
ALGOL 68
PROC multiply = ( LONG REAL a, b ) LONG REAL:
(
a * b
)
ALGOL W
long real procedure multiply( long real value a, b );
begin
a * b
end
ALGOL-M
This implementation takes two integers and returns an integer. Note that a function is distinguished from a procedure, which does not return a value.
INTEGER FUNCTION MULTIPLY( A, B );
INTEGER A, B;
BEGIN
MULTIPLY := A * B;
END;
Amazing Hopper
Hopper has no functions, but they can be declared with macros, which are resolved at compile time. Access to the working stack is global, but "local" variables can be declared in program segments written after the ".locals" clause. Let's look at some examples of declaring "functions".
/* this need data into stack */
#context Multiplication
mul
Return \\
#synon Multiplication *getproduct
#context-free anothermul
/* #defn Args(*) #GENCODE $$$*$$$ #REVLIST=0,mov(#REVLIST);#ENDGEN, */
Args 'a,b'
Return ( #(a*b) )\\
#synon anothermul *getanotherproduct
#include <jambo.h>
#prototype _multiply(_X_,_Y_)
#synon __multiply Multiply
Main
/* "prototipos" of functions and procedures.
Solves internaly */
Printnl ( Multiply ( 10, 4 ) )
Printnl ( __multiply ( 10, 4 ) )
/* definición alternativa 1 */
Printnl ( Set' 10,4 ', Gosub ' Multiply2 ')
/* aseembler Hopper 1 */
{10,4} jsub( Multiply3 ), {"\n"} print
/* assembler Hopper 2 */
{10,4} jsub( Multiply4 ), {"\n"} print
/* context */
Set '10,4', now get product, and print with newline
/* context-free */
Set '10,4', and get another product; then print with newline
End
.locals /* Subrutines */
_multiply(a,b)
Return ( Mul(a,b) )
/* Define is macro. Others macros: Function, Procedure:
#defn Define(_F_,*) _F_:,#GENCODE $$$*$$$ #REVLIST=0;mov(#REVLIST);#ENDGEN;
#defn Function(_F_,*) _F_:,#GENCODE $$$*$$$ #REVLIST=0;mov(#REVLIST);#ENDGEN;
#defn Procedure(_F_,*) _F_:,#GENCODE $$$*$$$ #REVLIST=0;mov(#REVLIST);#ENDGEN;
*/
Define 'Multiply2, a,b'
Return ( Mul(a,b) )
Multiply3:
b=0, mov(b), a=0, mov(a)
{a,b}mul /* result into stack */
Return
Multiply4:
mul /* get values from stack,
and put result into stack */
back /* Return */
- Output:
40.000000 40.000000 40.000000 40.000000 40.000000 40.000000 40.000000
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
AntLang
multiply: * /`*' is a normal function
multiply: {x * y}
Explicit definition has the syntax:
{expr-or-def1; expr-or-def2; ..; return-expr}
Inside functions, the variable args contains the sequence of arguments. x, y and z contain the first, second and third argument.
APL
⍝⍝ APL2 'tradfn' (traditional function)
⍝⍝ This syntax works in all dialects including GNU APL and Dyalog.
∇ product ← a multiply b
product ← a × b
∇
⍝⍝ A 'dfn' or 'lambda' (anonymous function)
multiply ← {⍺×⍵}
⍝⍝ Dyalog dfn (lambda) syntax
multiply ← ×
Works on arrays of any rank (any number of dimensions): atoms, lists, tables, etc.
AppleScript
to multiply(a as number, b as number)
return a * b
end
A function in AppleScript is called a "handler". It can take one of three different forms, depending on what the scripter finds most convenient. Calls to it must match the form used in the handler definition. Either to
or on
may be used as the first word in the handler definition. When the script is compiled, the handler label is automatically appended to the end
line too if it wasn't written in.
Handler names followed by zero or more parameters within parentheses are called "positional" -- the number and order of the parameters in the caller must match those in the handler definition.
on multiply(a, b)
return a * b
end multiply
multiply(2, 3)
AppleScript also offers handlers with "prepositional" labeled parameters. These aren't used often because the set of AppleScript-defined prepositions makes it difficult to choose ones that make sense in English.
These prepositions can be used: about, above, against, apart from, around, aside from, at, below, beneath, beside, between, by, for, from, instead of, into, on, onto, out of, over, since, thru, through, and under
. Also, of
is available, but if used it must be the first parameter.
Example:
on multiplication of a by b
return a * b
end multiplication
multiplication of 2 by 3 -- Or: (multiplication by 3) of 2, or: 2's (multiplication by 3)
Labeled parameters don't need to be in the same order in the calls as in the handler definition, but of
, if used, is regarded as a direct parameter and requires some parenthesis if it's not given first or if the context isn't entirely clear.
For the past few years, handlers with "interleaved" parameters have also been possible. They're a development from AppleScriptObjectiveC and coders can specify their own labels provided these aren't reserved words. Calls to these handlers must reference the handlers' "owners", which are usually represented within the same script by the keyword my
. The parameter order is the same in the calls as in the handler definitions:
on multiply:a |by|:b -- 'by' is "barred" here because otherwise it's a reserved word.
return a * b
end multiply:|by|:
my multiply:2 |by|:3
Argile
use std
.: multiply <real a, real b> :. -> real {a * b}
with a macro and a variable number of parameters:
use std
=: multiply <real a> [<real b>...] := -> real {Cgen a (@@1 (Cgen " * " b))}
ARM Assembly
/* ARM assembly Raspberry PI */
/* program functMul.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/***********************/
/* Initialized data */
/***********************/
.data
szRetourLigne: .asciz "\n"
szMessResult: .ascii "Resultat : " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/***********************
/* No Initialized data */
/***********************/
.bss
.text
.global main
main:
push {fp,lr} /* save 2 registers */
@ function multiply
mov r0,#8
mov r1,#50
bl multiply @ call function
ldr r1,iAdrsMessValeur
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
mov r0, #0 @ return code
100: /* end of program */
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* Function multiply */
/******************************************************************/
/* r0 contains value 1 */
/* r1 contains value 2 */
/* r0 return résult */
multiply:
mul r0,r1,r0
bx lr /* return function */
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* conversion register in string décimal signed */
/***************************************************/
/* r0 contains the register */
/* r1 contains address of conversion area */
conversion10S:
push {fp,lr} /* save registers frame and return */
push {r0-r5} /* save other registers */
mov r2,r1 /* early storage area */
mov r5,#'+' /* default sign is + */
cmp r0,#0 /* négatif number ? */
movlt r5,#'-' /* yes sign is - */
mvnlt r0,r0 /* and inverse in positive value */
addlt r0,#1
mov r4,#10 /* area length */
1: /* conversion loop */
bl divisionpar10 /* division */
add r1,#48 /* add 48 at remainder for conversion ascii */
strb r1,[r2,r4] /* store byte area r5 + position r4 */
sub r4,r4,#1 /* previous position */
cmp r0,#0
bne 1b /* loop if quotient not equal zéro */
strb r5,[r2,r4] /* store sign at current position */
subs r4,r4,#1 /* previous position */
blt 100f /* if r4 < 0 end */
/* else complete area with space */
mov r3,#' ' /* character space */
2:
strb r3,[r2,r4] /* store byte */
subs r4,r4,#1 /* previous position */
bge 2b /* loop if r4 greather or equal zero */
100: /* standard end of function */
pop {r0-r5} /*restaur others registers */
pop {fp,lr} /* restaur des 2 registers frame et return */
bx lr
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save autres registres */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667
ArnoldC
LISTEN TO ME VERY CAREFULLY multiply
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE product
YOU SET US UP @I LIED
GET TO THE CHOPPER product
HERE IS MY INVITATION a
YOU'RE FIRED b
ENOUGH TALK
I'LL BE BACK product
HASTA LA VISTA, BABY
Arturo
multiply: $[x,y][x*y]
print multiply 3 7
multiply2: function [x,y][
return x*y
]
print multiply2 3 7
- Output:
21 21
AutoHotkey
MsgBox % multiply(10,2)
multiply(multiplicand, multiplier) {
Return (multiplicand * multiplier)
}
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
AWK
function multiply(a, b)
{
return a*b
}
BEGIN {
print multiply(5, 6)
}
Axe
Lbl MULT
r₁*r₂
Return
BASIC
ANSI BASIC
In ANSI BASIC, functions can be defined as either formulas or multi-line external or internal subroutines. External functions are independent program units that can be called from within the program. Internal functions are considered part of the program unit they are contained in and can only be called from within that unit. External functions do not share any information with other program units and exchange information through parameters and returned values. Internal functions share everything with their surrounding program unit except for their parameters. Internal functions do not have local variables.
100 DEF Multiply(A, B) = A * B
110 DECLARE FUNCTION MultiplyI
120 DECLARE EXTERNAL FUNCTION MultiplyE
130 PRINT Multiply(3, 1.23456)
140 PRINT MultiplyI(3, 1.23456)
150 PRINT MultiplyE(3, 1.23456)
160 FUNCTION MultiplyI(X, Y)
170 LET MultiplyI = X * Y
180 END FUNCTION
190 END
200 EXTERNAL FUNCTION MultiplyE(A, B)
210 LET MultiplyE = A * B
220 END FUNCTION
- Output:
3.70368 3.70368 3.70368
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.
10 DEF FN MULTIPLY(P) = P(P) * P(P+1)
20 P(1) = 611 : P(2) = 78 : PRINT FN MULTIPLY(1)
47658
BASIC256
function multiply(a, b)
return a * b
end function
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:
PRINT FNmultiply(6,7)
END
DEF FNmultiply(a,b) = a * b
Multiline function:
DEF FNmultiply(a,b)
LOCAL c
c = a * b
= c
Chipmunk Basic
10 rem Function definition
20 rem ** 1. Function defined as formula. An obsolete way - does not work properly with integer formal parameters (e.g. x%).
30 def fnmultiply(a, b) = a * b
40 rem ** Call the functions
50 print multiply(3,1.23456)
60 print fn multiply(3,1.23456)
70 end
200 rem ** 2. Function defined as subroutine returning a value
210 sub multiply(a,b)
220 multiply = a*b
230 end sub
- Output:
3.70368 3.70368
Commodore BASIC
In Commodore BASIC function definition can consist of any mathematical operation other functions or commands which result in a numeric expression. The definition is limited to single statement, and it accepts only a single argument. When using the function, keyword fn must precede the function name, which itself must be uniquely distinguishable by its first two characters.
10 DEF FN MULT(X) = X*Y
20 Y = 4 : REM VALUE OF SECOND ARGUMENT MUST BE ASSIGNED SEPARATELY
30 PRINT FN MULT(3)
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.
FreeBASIC
' FB 1.05.0 Win64
Function multiply(d1 As Double, d2 As Double) As Double
Return d1 * d2
End Function
This function could either be used for all numeric types (as they are implicitly convertible to Double) or could be overloaded to deal with each such type (there are 12 of them).
Alternatively, one could write a macro though this wouldn't be type-safe:
#Define multiply(d1, d2) (d1) * (d2)
FutureBasic
window 1
local fn multiply( a as long, b as long ) as long
end fn = a * b
print fn multiply( 3, 9 )
HandleEvents
Output:
27
Gambas
Click this link to run this code
Public Sub Main()
Print Multiply(56, 4.66)
End
Public Sub Multiply(f1 As Float, f2 As Float) As Float
Return f1 * f2
End
Output:
260.96
GW-BASIC
10 DEF FNMULT(X,Y)=X*Y
20 PRINT FNMULT(5,6)
39 END
IS-BASIC
100 DEF MULTIPLY(A,B)=A*B
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)
PRINT
'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)
PRINT
'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))
PRINT
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
Liberty BASIC
' define & call a function
print multiply( 3, 1.23456)
wait
function multiply( m1, m2)
multiply =m1 *m2
end function
end
Locomotive Basic
10 DEF FNmultiply(x,y)=x*y
20 PRINT FNmultiply(2,PI)
Function names are always preceded by "FN" in Locomotive BASIC. Also, PI is predefined by the interpreter as 3.14159265.
OxygenBasic
'SHORT FORMS:
float multiply(float a,b) = a * b
float multiply(float a,b) { return a * b}
'BASIC FORM:
function multiply(float a, float b) as float
return a * b
end function
'BASIC LEGACY FORM:
function multiply(byval a as float, byval b as float) as float
function = a * b
end function
'TEST:
print multiply(pi,2) '6.28...
PureBasic
Procedure multiply(a,b)
ProcedureReturn a*b
EndProcedure
QBasic
'This function could either be used for all numeric types
'(as they are implicitly convertible to Double)
FUNCTION multiply# (a AS DOUBLE, b AS DOUBLE)
multiply = a * b
END FUNCTION
'
' Alternatively, it can be expressed in abbreviated form :
'
DEF FNmultiply# (a AS DOUBLE, b AS DOUBLE) = a * b
PRINT multiply(3, 1.23456)
PRINT FNmultiply#(3, 1.23456)
- Output:
3.703680038452148
QuickBASIC
DECLARE FUNCTION multiply% (a AS INTEGER, b AS INTEGER)
FUNCTION multiply% (a AS INTEGER, b AS INTEGER)
multiply = a * b
END FUNCTION
REALbasic
Function Multiply(a As Integer, b As Integer) As Integer
Return a * b
End Function
S-BASIC
S-BASIC is unusual in that the function return value is assigned to the END statement that terminates the function.
function multiply(a, b = integer) = integer
end = a * b
rem - exercise the function
print "The product of 9 times 3 is"; multiply(9, 3)
end
- Output:
The product of 9 times 3 is 27
SmallBASIC
func multiply(a, b)
return a * b
end
print "2 * 3 = "; multiply(2, 3)
If function definition is only one line, def
can be used:
def multiply(a, b) = a * b
print "2 * 3 = "; multiply(2, 3)
True BASIC
The FUNCTION
and DEF
commands are synonymous and can be interchanged.
FUNCTION multiply(a, b)
LET multiply = a * b
END FUNCTION
!
! Alternatively, it can be expressed in abbreviated form :
!
DEF multiply (a, b) = a * b
END
TI-89 BASIC
multiply(a, b)
Func
Return a * b
EndFunc
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.
Print FUNC(_multiply (23, 65))
End
_multiply Param (2) : Return (a@ * b@)
VBA
Function Multiply(lngMcand As Long, lngMplier As Long) As Long
Multiply = lngMcand * lngMplier
End Function
To use this function :
Sub Main()
Dim Result As Long
Result = Multiply(564231, 897)
End Sub
VBScript
function multiply( multiplicand, multiplier )
multiply = multiplicand * multiplier
end function
Usage:
dim twosquared
twosquared = multiply(2, 2)
Visual Basic
Function multiply(a As Integer, b As Integer) As Integer
multiply = a * b
End Function
Call the function
Multiply(6, 111)
Visual Basic .NET
Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer
Return a * b
End Function
Call the function
Multiply(1, 1)
Yabasic
sub multiply(a, b)
return a * b
end sub
Xojo
Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer
Return a * b
End Function
Call the function
Dim I As Integer = Multiply(7, 6)
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
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
Batch File
Windows batch files only have procedures, not functions. Instead, environmental variables can be used as a global shared state.
@ECHO OFF
SET /A result = 0
CALL :multiply 2 3
ECHO %result%
GOTO :eof
:multiply
SET /A result = %1 * %2
GOTO :eof
:eof
bc
define multiply(a, b) { return a*b }
print multiply(2, 3)
BCPL
A function is simply defined as an expression in terms of its arguments.
let multiply(a, b) = a * b
Defining a block of code that executes some statements and then returns a
result, is done with a separate valof
construct, which can
appear wherever an expression may appear, but which is mostly used
to define a function containing imperative statements. When used this way,
it is equivalent to the functions in most other imperative languages.
let multiply(a, b) = valof
$( // any imperative statements could go here
resultis a * b
$)
BlitzMax
function multiply:float( a:float, b:float )
return a*b
end function
print multiply(3.1416, 1.6180)
- Output:
5.08310890
Boo
def multiply(x as int, y as int):
return x * y
print multiply(3, 2)
Binary Lambda Calculus
In lambda calculus, multiplication on Church numerals is mul = \m \n \f. m (n f)
which in BLC is
00 00 00 01 1110 01 110 10
If mul is used several times within an expression E, then they can share the same definition by using (\mul. E)(\m\n\f. m (n f))
. For example, the cube function is \n. (\mul. mul n (mul n n)) (\m\n\f. m (n f))
which in BLC is
00 01 00 01 01 10 110 01 01 10 110 110 0000000111100111010
BQN
Tacit definition:
Multiply ← ×
With names:
Multiply ← {𝕨×𝕩}
Bracmat
multiply=a b.!arg:(?a.?b)&!a*!b;
out$multiply$(123456789.987654321); { writes 121932631112635269 to standard output }
Brat
multiply = { x, y | x * y }
p multiply 3 14 #Prints 42
C
double multiply(double a, double b)
{
return a * b;
}
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).
#define MULTIPLY(X, Y) ((X) * (Y))
Parentheses should be added around parameters in the function definition to avoid order of operations errors when someone uses the macro as such:
x = MULTIPLY(x + z, y);
A program with that call would be compiled as if this were coded instead:
x = ((x + z) * (y));
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#
static double multiply(double a, double b)
{
return a * b;
}
Anonymous function:
Func<double, double, double> multiply = ((a,b) => a*b);
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:
inline double multiply(double a, double b)
{
return a*b;
}
If not only doubles, but numbers of arbitrary types are to be multiplied, a function template can be used:
template<typename Number>
Number multiply(Number a, Number b)
{
return a*b;
}
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.
Since C++20, the template parameters can be inferred using auto:
auto multiply(auto a, auto b)
{
return a*b;
}
Chapel
proc multiply(a, b)
{
return a * b;
}
Can require that the two arguments be of the same type.
proc multiply(a : ?t ... 2)
{
return a(0) * a(1)
}
Will work on any type where the * operator is defined.
ChucK
fun float multiply (float a, float b)
{
return a * b;
}
// uncomment next line and change values to test
//<<< multiply(16,4) >>>;
Clay
multiply(x,y) = x * y;
Clojure
(defn multiply [x y]
(* x y))
(multiply 4 5)
Or with multiple arities (in the manner of the actual * function):
(defn multiply
([] 1)
([x] x)
([x y] (* x y))
([x y & more]
(reduce * (* x y) more)))
(multiply 2 3 4 5) ; 120
CLU
The following is a function that multiplies two integers and ignores any error conditions (as most examples do).
multiply = proc (a, b: int) returns (int)
return(a * b)
end multiply
The following is a type-parameterized function that wraps the built-in multiplication operator
faithfully, rethrows any exceptions, and works for any type that supports multiplication.
It also shows the complete syntax of a function definition (type parameterization,
signals, and a where
clause).
multiply = proc [T: type] (a, b: T) returns (T)
signals (overflow, underflow)
where T has mul: proctype (T, T) returns (T)
signals (overflow, underflow)
return(a * b) resignal overflow, underflow
end multiply
COBOL
In COBOL, multiply is a reserved word, so the requirements must be relaxed to allow a different function name.
The following uses a subprogram:
IDENTIFICATION DIVISION.
PROGRAM-ID. myTest.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 x PICTURE IS 9(3) VALUE IS 3.
01 y PICTURE IS 9(3) VALUE IS 2.
01 z PICTURE IS 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 PICTURE IS 9(3).
01 y PICTURE IS 9(3).
01 z PICTURE IS 9(9).
PROCEDURE DIVISION USING BY REFERENCE x, y, z.
MULTIPLY x BY y GIVING z.
EXIT PROGRAM.
END PROGRAM myMultiply.
This example uses user-defined functions.
IDENTIFICATION DIVISION.
PROGRAM-ID. myTest.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION myMultiply.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 x PICTURE IS 9(3) VALUE IS 3.
01 y PICTURE IS 9(3) VALUE IS 2.
PROCEDURE DIVISION.
DISPLAY myMultiply(x, y).
STOP RUN.
END PROGRAM myTest.
IDENTIFICATION DIVISION.
FUNCTION-ID. myMultiply.
DATA DIVISION.
LINKAGE SECTION.
01 x PICTURE IS 9(3).
01 y PICTURE IS 9(3).
01 z PICTURE IS 9(9).
PROCEDURE DIVISION USING x, y RETURNING z.
MULTIPLY x BY y GIVING z.
GOBACK.
END FUNCTION myMultiply.
Coco
As CoffeeScript. In addition, Coco provides some syntactic sugar for accessing the arguments
array reminiscent of Perl's @_
:
multiply = -> @@0 * @@1
Furthermore, when no parameter list is defined, the first argument is available as it
:
double = -> 2 * it
CoffeeScript
multiply = (a, b) -> a * b
ColdFusion
Tag style
<cffunction name="multiply" returntype="numeric">
<cfargument name="a" type="numeric">
<cfargument name="b" type="numeric">
<cfreturn a * b>
</cffunction>
Script style
numeric function multiply(required numeric a, required numeric b){
return a * b;
}
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.
(defun multiply (a b)
(* a b))
(multiply 2 3)
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:
(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!
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.
;;; terrific example coming
Cowgol
sub multiply(a: int32, b: int32): (rslt: int32) is
rslt := a * b;
end sub
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);
}
Both the compile-time and run-time output:
6 2 * 3 = 6
Dart
main(){
print(multiply(1,2));
print(multiply2(1,2));
print(multiply3(1,2));
}
// the following definitions are equivalent
// arrow syntax without type annotations
multiply(num1, num2) => num1 * num2;
// arrow syntax with type annotations
int multiply2(int num1, int num2) => num1 * num2;
// c style with curly braces
int multiply3(int num1, int num2){
return num1 * num2;
}
dc
For dc, the functions (called macros) are limited to names from 'a' to 'z' Create a function called 'm'
[*] sm
Use it (lm loads the function in 'm',x executes it, f shows the the stack.)
3 4 lm x f
= 12
Delphi
In addition to what is shown in the section Pascal, the following is possible too:
function multiply(a, b: integer): integer;
begin
result := a * b;
end;
Diego
begin_funct({number}, multiply)_param({number}, a, b);
with_funct[]_calc([a]*[b]);
end_funct[];
me_msg()_funct(multiply)_param(1,2);
DM
Functions (called procs) may be derived from proc
.
proc/multiply(a, b)
return a * b
Draco
Draco does not have the equivalent of a return
statement.
Instead, the last statement in a function must be an expression of the
return type of the function.
proc multiply(word a, b) word:
a * b
corp
Dragon
func multiply(a, b) {
return a*b
}
DWScript
function Multiply(a, b : Integer) : Integer;
begin
Result := a * b;
end;
Dyalect
func multiply(a, b) {
a * b
}
Using lambda syntax:
let multiply = (a, b) => a * b
Déjà Vu
multiply a b:
* a b
E
def multiply(a, b) {
return a * b
}
(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:
def multiply := fn a, b { a * b }
This definition is identical to the previous except that the function object will not know its own name.
EasyLang
func multiply a b .
return a * b
.
print multiply 7 5
EchoLisp
(define (multiply a b) (* a b)) → multiply ;; (1)
(multiply 1/3 666) → 222
;; a function is a lambda definition :
multiply
→ (λ (_a _b) (#* _a _b))
;; The following is the same as (1) :
(define multiply (lambda(a b) (* a b)))
multiply
→ (🔒 λ (_a _b) (#* _a _b)) ;; a closure
;; a function may be compiled
(lib 'compile)
(compile 'multiply "-float-verbose")
→
💡 [0] compiling _🔶_multiply ((#* _a _b))
;; object code (javascript) :
var ref,top = _blocks[_topblock];
/* */return (
/* */(_stack[top] *_stack[1 + top])
/* */);
multiply → (λ (_a _b) (#🔶_multiply)) ;; compiled function
Ecstasy
module MultiplyExample {
static <Value extends Number> Value multiply(Value n1, Value n2) {
return n1 * n2;
}
void run() {
(Int i1, Int i2) = (7, 3);
Int i3 = multiply(i1, i2);
(Double d1, Double d2) = (2.7182818, 3.1415);
Double d3 = multiply(d1, d2);
@Inject Console console;
console.print($"{i1}*{i2}={i3}, {d1}*{d2}={d3}");
}
}
- Output:
7*3=21, 2.7182818*3.1415=8.539482274700001
Efene
multiply = fn (A, B) {
A * B
}
@public
run = fn () {
io.format("~p~n", [multiply(2, 5)])
}
Eiffel
multiply(a, b: INTEGER): INTEGER
do
Result := a*b
end
Ela
multiply x y = x * y
Anonymous function:
\x y -> x * y
Elena
real multiply(real a, real b)
= a * b;
Anonymous function / closure:
symbol f = (x,y => x * y);
Root closure:
f(x,y){ ^ x * y }
Elixir
defmodule RosettaCode do
def multiply(x,y) do
x * y
end
def task, do: IO.puts multiply(3,5)
end
RosettaCode.task
- Output:
15
Elm
--There are multiple ways to create a function in Elm
--This is a named function
multiply x y = x*y
--This is an anonymous function
\x y -> x*y
Emacs Lisp
(defun multiply (x y)
(* x y))
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.
(defun multiply (x y)
"Return the product of X and Y."
(* x y))
EMal
fun multiply = var by var a, var b
return a * b
end
writeLine(multiply(6, 7))
writeLine(multiply("can", 2))
- Output:
42 cancan
Erlang
Using case, multiple lines
% 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.
- Output:
12 ok
In a single line
-module(func_definition).
-export([main/0]).
main() ->
K=multiply(3,4),
io :format("~p~n",[K]).
multiply(A,B) -> A * B.
The output is the same.
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
function multiply( atom a, atom b )
return a * b
end function
If you declare the arguments as object
then sequence comprehension kicks in:
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 )
- 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:
let multiply x y = x * y // integer
let fmultiply (x : float) (y : float) = x * y
Factor
: multiply ( a b -- a*b ) * ;
Falcon
function sayHiTo( name )
> "Hi ", name
end
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}
Fantom
class FunctionDefinition
{
public static Void main ()
{
multiply := |Int a, Int b -> Int| { a * b }
echo ("Multiply 2 and 4: ${multiply(2, 4)}")
}
}
Fermat
Func Multiply(a, b) = a*b.
Fexl
\multiply=(\x\y * x y)
Or if I'm being cheeky:
\multiply=*
Fish
Functions cannot be named in Fish. However, they can be defined as new stacks that pull a certain number of arguments off the stack that came before. 2[
says pull 2 values off the stack and put them in a new, separate stack. ]
says put all remaining values in the current stack onto the top of the stack below (the old stack).
2[*]
Forth
: fmultiply ( F: a b -- F: c ) F* ;
: multiply ( a b -- c ) * ;
Fortran
In FORTRAN I (1957), inline function could be defined at the beginning of the program. Let's note than to specify a floating point real the name of the statement function begins with an X (no type declaration) and to specify this is a function the name ends with a F.
XMULTF(X,Y)=X*Y
And for interger multiplication:
MULTF(I,J)=I*J
In FORTRAN IV, FORTRAN 66 or later, define a function:
FUNCTION MULTIPLY(X,Y)
REAL MULTIPLY, X, Y
MULTIPLY = X * Y
END
And for integer multiplication:
FUNCTION MULTINT(X,Y)
INTEGER MULTINT, X, Y
MULTINT = X * Y
END
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:
module elemFunc
contains
elemental function multiply(x, y)
real, intent(in) :: x, y
real :: multiply
multiply = x * y
end function multiply
end module elemFunc
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
It is worth noting that Fortran can call functions (and subroutines) using named arguments; e.g. we can call multiply in the following way:
c = multiply(y=b, x=a) ! the same as multiply(a, b)
z = multiply(y=x, x=y) ! the same as multiply(y, x)
(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:
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
Free Pascal
Free Pascal allows everything what Delphi allows. Note, using the special variable “result” requires {$modeSwitch result+}. This is the default in {$mode objFPC} and {$mode Delphi}.
Furthermore, after the assignment to the return variable further statements may follow. To ensure a value is returned immediately and no further following statements are processed, using the built-in exit procedure is possible too in {$mode objFPC}:
function multiply(a, b: integer): integer;
begin
exit(a * b);
end;
If exit has been redefined in the current scope, its special meaning can be accessed via the fully-qualified identifier system.exit. Note, any enclosing finally frames of try … finally … end are processed first before actually returning from the function. As a consequence of that, exit may not appear within a finally frame.
Frink
This function works correctly with any combination of arbitrarily-large integers, arbitrary-precision floating point numbers, arbitrary-size rational numbers, complex numbers, intervals of real numbers, and even numbers with units of measure (e.g. multiply[1 watt, 1 s]
gives an answer with dimensions of energy. Frink tries hard to always Do The Right Thing with math and numerics and units of measure.
multiply[x,y] := x*y
Futhark
let multiply (x: i32, y: i32) : i32 = x * y
GAP
multiply := function(a, b)
return a*b;
end;
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:
#define multiply
a = argument0
b = argument1
return(a * b)
Gnuplot
multiply(x,y) = x*y
# then for example
print multiply(123,456)
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:
func multiply(a, b float64) float64 {
return a * b
}
Alternatively, if the return value is named, the return statement does not require an expression:
func multiply(a, b float64) (z float64) {
z = a * b
return
}
Golfscript
{*}:multiply;
Groovy
def multiply = { x, y -> x * y }
Test Program:
println "x * y = 20 * 50 = ${multiply 20, 50}"
- Output:
x * y = 20 * 50 = 1000
Halon
function multiply( $a, $b )
{
return $a * $b;
}
Haskell
multiply x y = x * y
Alternatively, with help of auto-currying,
multiply = (*)
You can use lambda-function
multiply = \ x y -> x*y
Haxe
function multiply(x:Float, y:Float):Float{
return x * y;
}
hexiscript
fun multiply a b
return a * b
endfun
HicEst
FUNCTION multiply(a, b)
multiply = a * b
END
HolyC
F64 Multiply(F64 a, F64 b) {
return a * b;
}
F64 x;
x = Multiply(42, 13.37);
Print("%5.2f\n", x);
Hy
Function definition:
(defn multiply [a b]
(* a b))
Lambda definition:
(def multiply (fn [a b] (* a b)))
i
concept multiply(a, b) {
return a*b
}
Icon and Unicon
IDL
The task description is unclear on what to do when the arguments to the function are non-scalar, so here's multiple versions:
function multiply ,a,b
return, a* b
end
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:
function multiply ,a,b
return, product([a, b])
end
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:
function multiply ,a,b
return, a # b
end
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
[ multiply a b;
return a * b;
];
Inform 7
To decide which number is (A - number) multiplied by (B - number):
decide on A * B.
Io
multiply := method(a,b,a*b)
J
multiply=: *
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):
multiply=: dyad define
x * y
)
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.
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; }
}
Using Java version 8
Since version 8, Java has various built in Functions with their normal mathematical names.
import java.util.function.BiFunction;
import java.util.function.DoubleUnaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public final class FunctionDefinition {
public static void main(String[] args) {
System.out.println(size.apply("Rosetta"));
System.out.println(greeting.apply("Joe"));
System.out.println(half.applyAsDouble(7));
System.out.println(lessThanTen.test(15));
System.out.println(add.apply(2, 3));
}
private static Function<String, Integer> size = s -> s.length();
private static UnaryOperator<String> greeting = s -> "Hello " + s;
private static DoubleUnaryOperator half = a -> a / 2;
private static Predicate<Integer> lessThanTen = a -> a < 10;
private static BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
}
- Output:
7 Hello Joe 3.5 false 5
JavaScript
ES1-*
Function Declaration
function multiply(a, b) {
return a*b;
}
ES3-*
Function Expression
var multiply = function(a, b) {
return a * b;
};
Named Function Expression
var multiply = function multiply(a, b) {
return a * b;
};
Method Definition
var o = {
multiply: function(a, b) {
return a * b;
}
};
ES5-*
Accessors
var o = {
get foo() {
return 1;
},
set bar(value) {
// do things with value
}
};
ES6-*
Arrow Function
var multiply = (a, b) => a * b;
var multiply = (a, b) => { return a * b };
// Or, `var` being long deprecated, and currying convenient,
// (particularly in use with the higher-order Array methods)
const multiply = a =>
b => a * b;
Concise Body Method Definition
var o = {
multiply(a, b) {
return a * b;
}
};
Generator Functions
function * generator() {
yield 1;
}
Joy
DEFINE multiply == * .
jq
Example of a simple function definition:
def multiply(a; b): a*b;
Example of the definition of an inner function:
# 2 | generate(. * .) will generate 2, 4, 16, 256, ...
def generate(f): def r: ., (f | r); r;
The previous example (generate/1) also illustrates that a function argument can be a function or composition of functions. Here is another example:
def summation(f): reduce .[] as $x (0; . + ($x|f));
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:
summation( .h * .w)
Julia
General function definition:
function multiply(a::Number, b::Number)
return a * b
end
Julia also supports `assignment` definition as shorthand:
multiply(a, b) = a * b
And lambda calculus:
multiply = (a, b) -> a * b
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) ));
}
Klingphix
:multiply * ;
2 3 multiply print { 6 }
Kotlin
// One-liner
fun multiply(a: Int, b: Int) = a * b
// Proper function definition
fun multiplyProper(a: Int, b: Int): Int {
return a * b
}
Lambdatalk
{def multiply
{lambda {:a :b}
{* :a :b}}}
{multiply 3 4}
-> 12
could be written as a variadic function:
{def any_multiply
{lambda {:n} // thanks to variadicity of *
{* :n}}}
{any_multiply 1 2 3 4 5 6}
-> 720
Lang
Function decleration
fp.multiply = ($a, $b) -> {
return parser.op($a * $b)
}
One-line function decleration
fp.multiply = ($a, $b) -> return parser.op($a * $b)
Function decleration by using operator functions
fp.multiply = fn.mul
Function decleration by using combinator functions
Combinator functions can be called partially, fn.argCnt2 is used to force the caller to provide 2 arguments to prevent partially calling fp.multiply
fp.multiply = fn.argCnt2(fn.combA2(fn.mul))
Function decleration with call by pointer
fp.multiply = ($[a], $[b]) -> {
return parser.op($*a * $*b) # Pointers can be dereferenced by using *
}
langur
val multiply = fn{*}
val multiply = fn a, b: a * b
val multiply = fn(a, b) { a * b }
Lasso
Lasso supports multiple dispatch — signature definitions determine which method will be invoked.
define multiply(a,b) => {
return #a * #b
}
As this function is so simple it can also be represented like so:
define multiply(a,b) => #a * #b
Using multiple dispatch, different functions will be invoked depending on the functions input.
// 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)
Latitude
Latitude methods are defined using curly braces {}
and assigned to variables like any other value. Arguments are implicitly named $1
, $2
, etc.
multiply := { $1 * $2. }.
Calling a method is done either with parentheses or with a colon.
multiply (2, 3).
multiply: 2, 3.
If a method is intended to be used as a first-class value or stored in a data structure, the automatic evaluation behavior of methods can be undesired. In this case, one can wrap a method in a Proc
with the proc
method. Proc
objects can then be later called explicitly with call
.
multiply := proc { $1 * $2. }.
multiply call (2, 3).
multiply call: 2, 3.
LDPL
data:
n is number
procedure:
sub multiply
parameters:
x is number
y is number
result is number
procedure:
in result solve x * y
end sub
# call the bare sub-procedure
call multiply with 3 4 n
display n lf
# create a statement for it
create statement "multiply $ by $ in $" executing multiply
multiply 3 by 4 in n
display n lf
- Output:
12 12
LFE
(defun mutiply (a b)
(* a b))
Lily
define multiply(a: Integer, b: Integer): Integer
{
return a * b
}
Lingo
on multiply (a, b)
return a * b
end
LiveCode
LiveCode has a built-in method called multiply, so there is an extra y to avoid an error.
function multiplyy n1 n2
return n1 * n2
end multiplyy
put multiplyy(2,5) -- = 10
Logo
to multiply :x :y
output :x * :y
end
LSE64
multiply : *
multiply. : *. # floating point
Lua
function multiply( a, b )
return a * b
end
Lucid
multiply(x,y) = x * y
M2000 Interpreter
A Module can return value
A module can return value to stack of values. Calling a module we place parent stack to module, so we can read any value.
Module Checkit {
Module Multiply (a, b) {
Push a*b
}
Multiply 10, 5
Print Number=50
Module Multiply {
Push Number*Number
}
Multiply 10, 5
Print Number=50
\\ push before call
Push 10, 5
Multiply
Read A
Print A=50
Push 10, 2,3 : Multiply : Multiply: Print Number=60
Module Multiply {
If not match("NN") Then Error "I nead two numbers"
Read a, b
Push a*b
}
Call Multiply 10, 5
Print Number=50
\\ now there are two values in stack 20 and 50
Multiply
}
Call Checkit, 20, 50
Print Number=1000
A Local Function Definition
There are two types of function, the normal and the lambda. If a Function return string then we have to use $ at the end of function name.
Module Checkit {
\\ functions can shange by using a newer definition
\\ function Multiply is local, and at the exit of Checkit, erased.
Function Multiply (a, b) {
=a*b
}
Print Multiply(10, 5)=50
Function Multiply {
=Number*Number
}
Print Multiply(10, 5)=50
Function Multiply {
If not match("NN") Then Error "I nead two numbers"
Read a, b
=a*b
}
Print Multiply(10, 5)=50
Function Multiply {
Read a as long, b as long
=a*b
}
Z=Multiply(10, 5)
Print Z=50, Type$(Z)="Long"
Function Multiply(a as decimal=1, b as decimal=2) {
=a*b
}
D=Multiply(10, 5)
Print D=50, Type$(D)="Decimal"
D=Multiply( , 50)
Print D=50, Type$(D)="Decimal"
D=Multiply( 50)
Print D=100, Type$(D)="Decimal"
\\ by reference plus using type
Function Multiply(&a as decimal, &b as decimal) {
=a*b
a++
b--
}
alfa=10@
beta=20@
D=Multiply(&alfa, &beta)
Print D=200, alfa=11,beta=19, Type$(D)="Decimal"
\\ Using Match() to identify type of items at the top of stack
Function MultiplyALot {
M=Stack
While Match("NN") {
mul=Number*Number
Stack M {
Data mul ' at the bottom
}
}
=Array(M)
}
K=MultiplyALot(1,2,3,4,5,6,7,8,9,10)
N=Each(K)
While N {
Print Array(N), ' we get 2 12 30 56 90
}
Print
}
Checkit
A Lambda Function
Lambda function is first citizen. We can push it to stack and make another reading from stack. Lambda can use closures as static variables, some of them are pointers so if we copy a lambda we just copy the pointer. Pointers are containers like pointer to array, inventory and stack. Here we define string lambda function (there is a numeric also)
Module CheckIt {
A$=Lambda$ N$="Hello There" (x) ->{
=Mid$(N$, x)
}
Print A$(4)="lo There"
Push A$
}
CheckIt
Read B$
Print B$(1)="Hello There"
Function List$ {
Dim Base 1, A$()
A$()=Array$([]) ' make an array from stack items
=lambda$ A$() (x) -> {
=A$(x)
}
}
\\ change definition/closures
B$=List$("Hello", "Rosetta", "Function")
Print B$(1)="Hello"
M4
define(`multiply',`eval($1*$2)')
multiply(2,3)
MAD
MAD supports two types of function declarations. One simply evaluates an expression:
INTERNAL FUNCTION MULT.(A,B) = A * B
Another allows multiple lines to be executed:
INTERNAL FUNCTION(A, B)
ENTRY TO MULT.
FUNCTION RETURN A * B
END OF FUNCTION
There are several quirks here. First, the length of any identifier must not be longer than six
characters, and the name of a function must end in a period (which does not count towards the length).
Therefore, the function is called MULT.
instead of multiply
.
Second, in a multi-line function it is actually the entry point that is named, and a function may have several separate entry points, which need not be at the beginning of the function. Control is transferred to whichever one is called.
Third, all variables are global to the compilation unit. In both examples above, A
and B
will be set to the values that are passed in, and they will persist after the function has run. They may be
declared elsewhere, or they will be of the default type (the NORMAL MODE
).
Make
In makefile, a function may be defined as a rule, with recursive make used to retrieve the returned value.
A=1
B=1
multiply:
@expr $(A) \* $(B)
Invoking it
make -f mul.mk multiply A=100 B=3
> 300
Using gmake, the define syntax is used to define a new function
A=1
B=1
define multiply
expr $(1) \* $(2)
endef
do:
@$(call multiply, $(A), $(B))
|gmake -f mul.mk do A=5 B=3
Maple
multiply:= (a, b) -> a * b;
Mathematica / Wolfram Language
There are two ways to define a function in Mathematica.
Defining a function as a transformation rule:
multiply[a_,b_]:=a*b
Defining a pure function:
multiply=#1*#2&
Maxima
f(a, b):= a*b;
MAXScript
fn multiply a b =
(
a * b
)
Mercury
% Module ceremony elided...
:- func multiply(integer, integer) = integer.
multiply(A, B) = A * B.
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
.
primarydef a mult b = a * b enddef;
t := 3 mult 5; show t; end
The primarydef allows to build binary operators with the same priority as *. For a more generic macro, we can use instead
def mult(expr a, b) = (a * b) enddef;
t := mult(2,3);
show t;
end
min
'*
is syntax sugar for (*)
, which is an anonymous function that takes two numbers from the data stack, multiplies them, and leaves the result on the data stack. To give it a name, we can use the :
sigil which is syntax sugar for define
.
'* :multiply
MiniScript
multiply = function(x,y)
return x*y
end function
print multiply(6, 7)
- Output:
42
MiniZinc
function var int:multiply(a: var int,b: var int) = a*b;
МК-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
PROCEDURE Multiply(a, b: INTEGER): INTEGER;
BEGIN
RETURN a * b
END Multiply;
Modula-3
PROCEDURE Multiply(a, b: INTEGER): INTEGER =
BEGIN
RETURN a * b;
END Multiply;
MUMPS
MULTIPLY(A,B);Returns the product of A and B
QUIT A*B
Nanoquery
def multiply(a, b)
return a * b
end
Neko
var multiply = function(a, b) {
a * b
}
$print(multiply(2, 3))
Output: 6
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)
}
NESL
function multiply(x, y) = x * y;
The NESL system responds by reporting the type it has inferred for the function:
multiply = fn : (a, a) -> a :: (a in number)
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
- 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
> (define (my-multiply a b) (* a b))
(lambda (a b) (* a b))
> (my-multiply 2 3)
6
Nial
Using variables
multiply is operation a b {a * b}
Using it
|multiply 2 3
=6
Point free form
mul is *
Using it
|mul 3 4
=12
Nial also allows creation of operators
multiply is op a b {a * b}
Using it.
|2 multiply 3
=6
|multiply 2 3
=6
Since this is an array programming language, any parameters can be arrays too
|mul 3 [1,2]
=3 6
|mul [1,2] [10,20]
=10 40
Nim
Nim has a magic variable, `result`, which can be used as a substitute for `return`. The `result` variable will be returned implicitly.
proc multiply(a, b: int): int =
result = a * b
Here is the same function but with the use of the `return` keyword.
proc multiply(a, b: int): int =
return a * b
The last statement in a function implicitly is the result value:
proc multiply(a, b: int): int = a * b
OASYS
method int multiply int x int y {
return x * y
}
OASYS Assembler
OASYS Assembler requires a prefix and suffix on names to indicate their types (an omitted suffix means a void type).
[&MULTIPLY#,A#,B#],A#<,B#<MUL RF
Oberon-2
Oberon-2 uses procedures, and has a special procedure called a "Function Procedure" used to return a value.
PROCEDURE Multiply(a, b: INTEGER): INTEGER;
BEGIN
RETURN a * b;
END Multiply;
Objeck
function : Multiply(a : Float, b : Float) ~, Float {
return a * b;
}
OCaml
let int_multiply x y = x * y
let float_multiply x y = x *. y
Octave
function r = mult(a, b)
r = a .* b;
endfunction
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 *
: multiply * ;
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 :
: multiply2(a, b) a b * ;
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.
Ol
Function creation implemented using keyword 'lambda'. This created anonymous function can be saved into local or global variable for further use.
(lambda (x y)
(* x y))
Ol has two fully equal definitions of global named function (second one is syntactic sugar for first one). In fact both of them is saving the created lambda in global variable.
(define multiply (lambda (x y) (* x y)))
(define (multiply x y) (* x y))
And only one definition of local named functions (with immediate calculation). This type of definition helps to implement local recursions.
(let multiply ((x n) (y m))
(* x y))
; example of naive multiplication function implementation using local recursion:
(define (multiply x y)
(let loop ((y y) (n 0))
(if (= y 0)
n
(loop (- y 1) (+ n x)))))
(print (multiply 7 8))
; ==> 56
OOC
multiply: func (a: Double, b: Double) -> Double {
a * b
}
ooRexx
Internal Procedure
SAY multiply(5, 6)
EXIT
multiply:
PROCEDURE
PARSE ARG x, y
RETURN x*y
::Routine Directive
say multiply(5, 6)
::routine multiply
use arg x, y
return x *y
Accomodate large factors
say multiply(123456789,987654321)
say multiply_long(123456789,987654321)
::routine multiply
use arg x, y
return x *y
::routine multiply_long
use arg x, y
Numeric Digits (length(x)+length(y))
return x *y
- Output:
1.21932631E+17 121932631112635269
OpenEdge/Progress
function multiply returns dec (a as dec , b as dec ):
return a * b .
end.
Oz
fun {Multiply X Y}
X * Y
end
Or by exploiting first-class functions:
Multiply = Number.'*'
PARI/GP
multiply(a,b)=a*b;
or
multiply=(a,b)->a*b;
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:
multiply={(a,b)->a*b;}
which will return a function which calculates but does not return the product.
Pascal
see also: Delphi and Free Pascal
function multiply(a, b: real): real;
begin
multiply := a * b
end;
After a function has been activated, there must have be exactly one assignment to the (implicitly declared) variable bearing the same name as of the function. Many processors do not comply with this specification, though, and allow overwriting the return value multiple times.
PascalABC.NET
function multiply(a,b: real): real := a + b;
Perl
The most basic form:
sub multiply { return $_[0] * $_[1] }
or simply:
sub multiply { $_[0] * $_[1] }
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:
sub multiply( $$ )
{
my ($a, $b) = @_;
return $a * $b;
}
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):
use experimental 'signatures';
sub multiply ($x, $y) {
return $x * $y;
}
Phix
with javascript_semantics function multiply(atom a, atom b) return a*b end function
Phixmonti
def multiply * enddef
PHL
@Integer multiply(@Integer a, @Integer b) [
return a * b;
]
PHP
function multiply( $a, $b )
{
return $a * $b;
}
Picat
multiply(A, B) = A*B.
PicoLisp
(de multiply (A B)
(* A B) )
Pike
int multiply(int a, int b){
return a * b;
}
PL/I
PRODUCT: procedure (a, b) returns (float);
declare (a, b) float;
return (a*b);
end PRODUCT;
PL/SQL
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;
Plain English
The Multiply a number by another number
routine is already defined in the noodle, so we need to tweak the wording slightly so the compiler doesn't complain about redefinition (or so the definition isn't recursive). Note that the number
refers to the parameter a number
and the other number
refers to the parameter another number
.
To multiply a number with another number:
Multiply the number by the other number.
Pop11
define multiply(a, b);
a * b
enddefine;
PostScript
Inbuilt:
3 4 mul
Function would be:
/multiply{
/x exch def
/y exch def
x y mul =
}def
PowerShell
The most basic variant of function definition would be the kind which uses positional parameters and therefore doesn't need to declare much:
function multiply {
return $args[0] * $args[1]
}
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":
function multiply {
$args[0] * $args[1]
}
Furthermore, the function arguments can be stated and named explicitly:
function multiply ($a, $b) {
return $a * $b
}
There is also an alternative style for declaring parameters. The choice is mostly a matter of personal preference:
function multiply {
param ($a, $b)
return $a * $b
}
And the arguments can have an explicit type:
function multiply ([int] $a, [int] $b) {
return $a * $b
}
Processing
Processing is based on Java, and thus uses a familiar C-style syntax for function definition—as it does for much else. For the sake of argument, this implementation of multiply uses single-precision floats: other numeral types are available.
float multiply(float x, float y)
{
return x * y;
}
Processing Python mode
Processing Python mode is based on Jython, a fully implemented Python 2 interpreter, and thus uses familiar Python syntax for function definition-as it does for much else.
def multiply(x, y):
return x * y
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):
multiply(A, B, P) :- P is A * B.
This is what it looks like in use:
go :-
multiply(5, 2, P),
format("The product is ~d.~n", [P]).
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:
test_multiply :-
multiply(5, 2, 10), % this will pass
multiply(3, 4, 11). % this will not pass
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.
:- 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)]).
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:
go :-
A is 5*2,
format('The product is ~d.~n', [A]).
Python
Function definition:
def multiply(a, b):
return a * b
Lambda function definition:
multiply = lambda a, b: a * b
A callable class definition allows functions and classes to use the same interface:
class Multiply:
def __init__(self):
pass
def __call__(self, a, b):
return a * b
multiply = Multiply()
print multiply(2, 4) # prints 8
(No extra functionality is shown in this class definition).
Q
multiply:{[a;b] a*b}
or
multiply:{x*y}
or
multiply:*
Using it
multiply[2;3]
6
Quack
You have several ways to define a function in Quack. You can do it by the classic way:
fn multiply[ a; b ]
^ a * b
end
Using lambda-expressions:
let multiply :- fn { a; b | a * b }
And using partial anonymous functions:
let multiply :- &(*)
Quackery
[ * ] is multiply ( n n --> n )
In the Quackery shell (REPL):
/O> 2 3 multiply ... Stack: 6
Quackery is a stack language: arguments are assumed to be on the stack when functions are called. This means that we don't need to name the parameters of a function. For this reason, we call functions words, because in code they really are just words written one after the other.
( n n --> n )
is a comment that indicates multiply
takes two numbers from the data stack and leaves one number on the data stack afterward. Stack comments are not necessary, but they are good form. They show how words interact with the data stack at a glance.
Words don't have to be named. We could have written the above as:
2 ' [ * ] 3 swap do
By quoting the nest containing *
with the '
word, we have prevented it from being executed immediately and placed it on the data stack. Now it can be manipulated like any other nest or data stack object. We can use do
to execute the contents of the nest.
R
mult <- function(a,b) a*b
In general:
mult <- function(a,b) {
a*b
# or:
# return(a*b)
}
Racket
A simple function definition that takes 2 arguments.
(define (multiply a b) (* a b))
Using an explicit lambda
or λ
is completely equivalent:
(define multiply (lambda (a b) (* a b)))
(define multiply (λ (a b) (* a b)))
Note that *
is a function value, so the following code also works (although multiply
will now be variadic function).
(define multiply *)
Raku
(formerly Perl 6) Without a signature:
sub multiply { return @_[0] * @_[1]; }
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:
sub multiply { [*] @_ }
With formal parameters and a return type:
sub multiply (Rat $a, Rat $b --> Rat) { $a * $b }
Same thing:
my Rat sub multiply (Rat $a, Rat $b) { $a * $b }
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:
my &multiply := -> $a, $b { $a * $b };
Another way to write a lambda is with internal placeholder parameters:
my &multiply := { $^a * $^b };
(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:
my &multiply := * * *;
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:
@list.grep( *.substr(0,1).lc.match(/<[0..9 a..f]>/) )
This is equivalent to:
@list.grep( -> $obj { $obj.substr(0,1).lc.match(/<[0..9 a..f]>/) } )
Raven
define multiply use a, b
a b *
Or optional infix:
define multiply use a, b
(a * b)
Or skip named vars:
define multiply *
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:
multiply: func [a b][a * b]
Relation
function multiply(a,b)
set result = a*b
end function
Retro
: multiply ( nn-n ) * ;
REXX
exactitudeness
multiply: return arg(1) * arg(2) /*return the product of the two arguments.*/
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.
multiply: return arg(1) * arg(2) / 1 /*return with a normalized product of 2 args. */
Ring
func multiply x,y return x*y
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:
>> class(sin)
function
>> type(sin)
builtin
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
f = function(x, y)
{
return x + y;
};
>> class(f)
function
>> type(f)
user
2. function can be member of a list (associative array)
somelist = <<>>;
somelist.f = function(x, y)
{
rval = x + y;
return rval;
};
3. user function which uses a function that is specified as a member of some list, here we use somelist from above:
g = function(x, y)
{
global(somelist);
rval = x * somelist.f(x, 2*y);
return rval;
};
RPL
≪ * ≫ 'MULT' STO 2 3 MULT
- Output:
6
Ruby
def multiply(a, b)
a * b
end
Ruby 3.0 adds endless method definition:
def multiply(a, b) = a * b
Rust
fn multiply(a: i32, b: i32) -> i32 {
a * b
}
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;
Scala
def multiply(a: Int, b: Int) = a * b
Scheme
(define multiply *)
Alternately,
(define (multiply a b)
(* a b))
Seed7
const func float: multiply (in float: a, in float: b) is
return a * b;
SenseTalk
put multiply(3,7) as words
to multiply num1, num2
return num1 * num2
end multiply
- Output:
twenty-one
SETL
proc multiply( a, b );
return a * b;
end proc;
Sidef
func multiply(a, b) {
a * b;
}
Simula
Simula uses the term procedure for subroutines/methods whether they return a value or not. A procedure that does return a value is declared with a data type (e.g. integer procedure), whereas one that does not is declared simply as procedure. This program defines multiply as an integer procedure and illustrates its use. Note that the second argument provided to Outint gives the width of the integer to be printed.
BEGIN
INTEGER PROCEDURE multiply(x, y);
INTEGER x, y;
BEGIN
multiply := x * y
END;
Outint(multiply(7,8), 2);
Outimage
END
Slate
define: #multiply -> [| :a :b | a * b].
or using a macro:
define: #multiply -> #* `er.
The block may also be installed as a method like so:
a@(Number traits) multiplyBy: b@(Number traits) [a * b].
or more explicitly (without sugar):
[| :a :b | a * b] asMethod: #multipleBy: on: {Number traits. Number traits}.
Smalltalk
|mul|
mul := [ :a :b | a * b ].
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
- 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.
+1>++2=@\=>+++3=@\==@\=.=# prints '6'
| | \=itoa=@@@+@+++++#
\=======!\==!/===?\<#
\>+<-/
SPARK
The function definition (multiplies two standard Integer):
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;
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 :
type Input_Type is range 0 .. 10;
type Result_Type is range 0 .. 100;
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:
package body Functions is
function Multiply (A, B : Integer) return Integer is
begin
return A * B;
end Multiply;
end Functions;
SPL
Single-line function definition:
multiply(a,b) <= a*b
Multi-line function definition:
multiply(a,b)=
x = a*b
<= x
.
SSEM
The SSEM instruction set makes no explicit provision for subroutines, and indeed its storage space is too small for them to be of much use; but something like a subroutine can be created using a modified form of Wheeler jump. In this technique, the jump to the subroutine is accomplished with the return address loaded in the accumulator. The first action by the subroutine is to store this address in a place where it will be found by its own final jump instruction. In principle, therefore, the subroutine can be called multiple times from different points in the program without the calling routine needing to modify it at all (or even to know anything about it beyond where it begins, where it expects to find its parameters, and where it will store its result or results).
In this example, the main routine does nothing at all beyond calling the subroutine and halting after it has returned. The values A and B are passed in the two addresses located immediately before the subroutine begins; their product is returned in the address that formerly stored A. Given that the multiply subroutine begins at address 8, the calling routine looks like this:
01000000000000100000000000000000 0. -2 to c
00100000000000000000000000000000 1. 4 to CI
01111111111111111111111111111111 2. -2
00000000000001110000000000000000 3. Stop
11100000000000000000000000000000 4. 7
or in pseudocode:
load &here jump multiply here: halt
Implementing multiply on the SSEM requires the use of repeated negation and subtraction. For the sake of example, the values 8 and 7 are provided for A and B.
00010000000000000000000000000000 6. 8
11100000000000000000000000000000 7. 7
11111000000001100000000000000000 8. c to 31
01100000000000100000000000000000 9. -6 to c
01111000000001100000000000000000 10. c to 30
01111000000000100000000000000000 11. -30 to c
01111000000001100000000000000000 12. c to 30
11100000000000100000000000000000 13. -7 to c
11100000000001100000000000000000 14. c to 7
11100000000000100000000000000000 15. -7 to c
00111000000000010000000000000000 16. Sub. 28
11100000000001100000000000000000 17. c to 7
00111000000000010000000000000000 18. Sub. 28
00000000000000110000000000000000 19. Test
00111000000001000000000000000000 20. Add 28 to CI
11111000000000000000000000000000 21. 31 to CI
01100000000000100000000000000000 22. -6 to c
01111000000000010000000000000000 23. Sub. 30
01100000000001100000000000000000 24. c to 6
01100000000000100000000000000000 25. -6 to c
01100000000001100000000000000000 26. c to 6
10111000000000000000000000000000 27. 29 to CI
10000000000000000000000000000000 28. 1
00110000000000000000000000000000 29. 12
00000000000000000000000000000000 30. 0
00000000000000000000000000000000 31. 0
The pseudocode equivalent clarifies how the subroutine works, or how it would work on an architecture that supported load and add:
a: equals #8 b: equals #7 multiply: store ret load a store n loop: load b sub #1 store b sub #1 ifNegative done load a add n store a jump loop done: jump *ret n: reserve 1 word ret: reserve 1 word
Standard ML
val multiply = op *
Equivalently,
fun multiply (x, y) = x * y
Using lambda syntax:
val multiply = fn (x, y) => x * y
Curried form:
fun multiply x y = x * y
Stata
Ado
Stata's macro language does not have functions, but commands. Output is usually saved as a "stored result" (but could also be saved in a global macro variable, in a scalar or matrix, in a dataset or simply printed to the Results window). See program and [1] in Stata documentation.
prog def multiply, return
args a b
return sca product=`a'*`b'
end
multiply 77 13
di r(product)
Output
1001
Mata
Mata is the matrix language of Stata. Here is how to define a function
mata
scalar multiply(scalar x, scalar y) {
return(x*y)
}
multiply(77,13)
end
Output
1001
Swift
func multiply(a: Double, b: Double) -> Double {
return a * b
}
Symstatic
You can write functions in let expressions or anonimously:
let prod(a, b) := a*b
let prodAnon := (a, b) -> a*b
assert(prodAnon(2, 2) = ((a, b) -> a*b)(2, 2))
assert(prod(2, 2) = prodAnon(2, 2))
Tcl
Strictly as described in the task:
proc multiply { arg1 arg2 } {
return [expr {$arg1 * $arg2}]
}
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):
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!"
}
Toka
[ ( ab-c ) * ] is multiply
Transd
multiply: (lambda a Double() b Double() (* a b))
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)
@(define multiply (a b out))
@(bind out @(* a b))
@(end)
@(multiply 3 4 result)
$ txr -B multiply.txr result="12"
In the embedded Lisp dialect, it is possible to write an ordinary function that returns a value:
(defun mult (a b) (* a b))
(put-line `3 * 4 = @(mult 3 4)`)
$ txr multiply.tl 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.
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
return an exit code
multiply() {
return $(($1 * $2))
}
multiply 5 6
echo $?
echo the result
multiply() {
echo -n $(($1 * $2))
}
echo $(multiply 5 6)
Ursa
# multiply is a built-in in ursa, so the function is called mult instead
def mult (int a, int b)
return (* a b)
end
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,
multiply = math..mul
this is the definition using lambda abstraction
multiply = ("a","b"). math..mul ("a","b")
and this is the definition using pattern matching.
multiply("a","b") = math..mul ("a","b")
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.
[multiply *].
Using it
2 3 multiply
=6
V also allows internal bindings.
[multiply
[a b] let
a b *].
V (Vlang)
fn multiply(a f64, b f64) f64 {
return a * b
}
fn main() {
print(multiply(5, 6))
}
- Output:
30.0
Wart
A straightforward way to say how calls of the form (multiply a b)
are translated:
def (multiply a b)
a*b
(multiply 3 4)
=> 12
Functions can also use keyword args.
(multiply 3 :a 4) # arg order doesn't matter here, but try subtract instead
=> 12
Finally, we can give parameters better keyword args using aliases:
def (multiply a b|by)
(* a b)
multiply 3 :by 4
=> 12
WebAssembly
(func $multipy (param $a i32) (param $b i32) (result i32) local.get $a local.get $b i32.mul )
Wren
The following 'multiply' function will work for any type(s) that support the '*' operator. However, it will produce a runtime error otherwise, as demonstrated by the final example.
var multiply = Fn.new { |a, b| a * b }
System.print(multiply.call(3, 7))
System.print(multiply.call("abc", 3))
System.print(multiply.call([1], 5))
System.print(multiply.call(true, false))
- Output:
21 abcabcabc [1, 1, 1, 1, 1] Bool does not implement '*(_)'. [./function_definition line 1] in new(_) block argument [./function_definition line 6] in (script)
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)
.
.text
.globl multiply
.type multiply,@function
multiply:
movl 4(%esp), %eax
mull 8(%esp)
ret
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
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
MASM
However, in MASM we do have function statements due to the preprocessor.
multiply proc arg1:dword, arg2:dword
mov eax, arg1
mov ebx, arg2
mul ebx
mov eax, ebx
ret
multiply endp
Then to call it.
invoke multiply, 6, 16
;or..
push 16
push 6
call multiply
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".
XBS
Functions are defined by using the func keyword.
func multiply(a,b){
send a*b;
}
XLISP
Functions can be defined using either 'classic' Lisp syntax:
(defun multiply (x y)
(* x y))
or Scheme-style syntax:
(define (multiply x y)
(* x y))
or, if you prefer, with LAMBDA:
(define multiply
(lambda (x y) (* x y)))
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;
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).
<xsl:template name="multiply">
<xsl:param name="a" select="2"/>
<xsl:param name="b" select="3"/>
<xsl:value-of select="$a * $b"/>
</xsl:template>
Usage examples.
<xsl:call-template name="multiply">
<xsl:with-param name="a">4</xsl:with-param>
<xsl:with-param name="b">5</xsl:with-param>
</xsl:call-template>
<xsl:call-template name="multiply"/> <-- using default parameters of 2 and 3 -->
Available in XSLT 2.0 and later versions.
<xsl:function name="mf:multiply">
<xsl:param name="a"/>
<xsl:param name="b"/>
<xsl:value-of select="$a * $b"/>
</xsl:function>
Usage examples.
{mf:multiply(2,3)}
<xsl:value-of select="mf:multiply(2,3)" />
YAMLScript
!yamlscript/v0
# Main function definition with variable arguments:
defn main(& args):
answer =:
multiply: ARGS*
say: "multiply($(ARGS.join(', '))) = $answer"
# A multi-arity function definition:
defn multiply:
(): 1
(x): x
(x y): x * y
(x y & more):
reduce multiply: multiply(x y) more
Yorick
func multiply(x, y) {
return x * y;
}
Example of interactive usage:
> multiply(2, 4.5) 9
Z80 Assembly
A function's return values are whatever registers or memory are changed by the function. A good programmer will explain what is returned where by using comments.
doMultiply:
;returns HL = HL times A. No overflow protection.
push bc
push de
rrca ;test if A is odd or even by dividing A by 2.
jr c, isOdd
;is even
ld b,a
loop_multiplyByEvenNumber:
add hl,hl ;double A until B runs out.
djnz loop_multiplyByEvenNumber
pop de
pop bc
ret
isOdd:
push hl
pop de ;de contains original HL. We'll need it later.
ld b,a
loop_multiplyByOddNumber:
add hl,hl
djnz loop_multiplyByOddNumber
add hl,de ;now add in original HL for the leftover add.
pop de
pop bc
ret
zig
fun multiply(x: i64, y: i64) i64 {
return x * y;
}
//example call
const x: i64 = 4;
const y: i64 = 23;
_ = multipy(x, y); // --> 93
zkl
fcn multiply(x,y){x*y}
fcn(x,y){x*y}(4.5,3) // --> 13.5
Since all functions are vararg:
fcn multiply{vm.arglist.reduce('*)}
multiply(1,2,3,4,5) //--> 120
Operators are first class objects so:
var mul=Op("*"); mul(4,5) //-->20
- Programming Tasks
- Basic language learning
- Functions and subroutines
- Simple
- 11l
- 360 Assembly
- 6502 Assembly
- 68000 Assembly
- 8051 Assembly
- 8086 Assembly
- AArch64 Assembly
- ACL2
- ActionScript
- Ada
- Aime
- ALGOL 60
- ALGOL 68
- ALGOL W
- ALGOL-M
- Amazing Hopper
- AmigaE
- AntLang
- APL
- AppleScript
- Argile
- ARM Assembly
- ArnoldC
- Arturo
- AutoHotkey
- AutoIt
- AWK
- Axe
- BASIC
- ANSI BASIC
- Applesoft BASIC
- BASIC256
- BBC BASIC
- Chipmunk Basic
- Commodore BASIC
- Creative Basic
- FreeBASIC
- FutureBasic
- Gambas
- GW-BASIC
- IS-BASIC
- IWBASIC
- Liberty BASIC
- Locomotive Basic
- OxygenBasic
- PureBasic
- QBasic
- QuickBASIC
- REALbasic
- S-BASIC
- SmallBASIC
- True BASIC
- TI-89 BASIC
- UBasic/4tH
- VBA
- VBScript
- Visual Basic
- Visual Basic .NET
- Yabasic
- Xojo
- ZX Spectrum Basic
- Batch File
- Bc
- BCPL
- BlitzMax
- Boo
- Binary Lambda Calculus
- BQN
- Bracmat
- Brat
- C
- C sharp
- C++
- Chapel
- ChucK
- Clay
- Clojure
- CLU
- COBOL
- Coco
- CoffeeScript
- ColdFusion
- Common Lisp
- Cowgol
- D
- Dart
- Dc
- Delphi
- Diego
- DM
- Draco
- Dragon
- DWScript
- Dyalect
- Déjà Vu
- E
- EasyLang
- EchoLisp
- Ecstasy
- Efene
- Eiffel
- Ela
- Elena
- Elixir
- Elm
- Emacs Lisp
- EMal
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Falcon
- FALSE
- Fantom
- Fermat
- Fexl
- Fish
- Forth
- Fortran
- Free Pascal
- Frink
- Futhark
- GAP
- GML
- Gnuplot
- Go
- Golfscript
- Groovy
- Halon
- Haskell
- Haxe
- Hexiscript
- HicEst
- HolyC
- Hy
- I
- Icon
- Unicon
- IDL
- Inform 6
- Inform 7
- Io
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- Kaya
- Klingphix
- Kotlin
- Lambdatalk
- Lang
- Langur
- Lasso
- Latitude
- LDPL
- LFE
- Lily
- Lingo
- LiveCode
- Logo
- LSE64
- Lua
- Lucid
- M2000 Interpreter
- M4
- MAD
- Make
- Maple
- Mathematica
- Wolfram Language
- Maxima
- MAXScript
- Mercury
- Metafont
- Min
- MiniScript
- MiniZinc
- МК-61/52
- Modula-2
- Modula-3
- MUMPS
- Nanoquery
- Neko
- Nemerle
- NESL
- NetRexx
- NewLISP
- Nial
- Nim
- OASYS
- OASYS Assembler
- Oberon-2
- Objeck
- OCaml
- Octave
- Oforth
- Ol
- OOC
- OoRexx
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHL
- PHP
- Picat
- PicoLisp
- Pike
- PL/I
- PL/SQL
- Plain English
- Pop11
- PostScript
- PowerShell
- Processing
- Processing Python mode
- Prolog
- Python
- Q
- Quack
- Quackery
- R
- Racket
- Raku
- Raven
- REBOL
- Relation
- Retro
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Rust
- Sather
- Scala
- Scheme
- Seed7
- SenseTalk
- SETL
- Sidef
- Simula
- Slate
- Smalltalk
- SNOBOL4
- SNUSP
- SPARK
- SPL
- SSEM
- Standard ML
- Stata
- Swift
- Symstatic
- Tcl
- Toka
- Transd
- TXR
- UNIX Shell
- Ursa
- Ursala
- V
- V (Vlang)
- Wart
- WebAssembly
- Wren
- X86 Assembly
- XBS
- XLISP
- XPL0
- XSLT
- YAMLScript
- Yorick
- Z80 Assembly
- Zig
- Zkl
- GUISS/Omit
- TI-83 BASIC/Omit
- Pages with too many expensive parser function calls