Function definition
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function.
Write a definition of a function called "multiply" that takes two arguments and returns their product.
Ada
<ada> function Multiply (A, B : Float) return Float; </ada> and an implementation of: <ada> function Multiply (A, B : Float) return Float is begin
return A * B;
end Multiply; </ada> Ada supports generic functions which can take generic formal parameters like the numeric type to use: <ada> generic
type Number is digits <>;
function Multiply (A, B : Number) return Number; </ada> implemented as: <ada> function Multiply (A, B : Number) return Number is begin
return A * B;
end Multiply; </ada>
ALGOL 68
PROC multiply = ( LONG REAL a, b ) LONG REAL: ( a * b )
APL
multiply ← ×
Works on arrays of any rank (any number of dimensions): atoms, lists, tables, etc.
BASIC
DECLARE FUNCTION multiply% (a AS INTEGER, b AS INTEGER) FUNCTION multiply% (a AS INTEGER, b AS INTEGER) multiply = a * b END FUNCTION
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). This is useful for less complex function as they won't take up any extra memory.
#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++
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.
Common Lisp
(defun multiply (a b) (* a b))
(multiply 2 3)
D
double multiply(double a, double b) { return a * b; }
or templated one:
T multiply(T)(T a, T b) { return a * b; }
Compile-time evaluation
Function "multiply" can be evaluated at compile time if appears in a context where only compile-time constant is valid:
const result = multiply(2, 3); // Evaluated at compile time writefln("2 * 3 = ", result);
Compile-time multiplication can also be done using template:
template multiply(int a, int b) { const multiply = a * b; }
Use it like this:
import std.metastrings; pragma (msg, ToString!(multiply!(2, 3))); // Prints "6" during program compilation
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
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.)
Forth
: fmultiply ( F: a b -- F: c ) F* ; : multiply ( a b -- c ) * ;
Fortran
In FORTRAN 66 or later, define a function:
FUNCTION MULTIPLY(X,Y) REAL MULTIPLY, X, Y MULTIPLY = 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
Haskell
multiply = (*)
Alternatively,
multiply = \ x y -> x*y
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.
Io
multiply := method(a,b,a*b)
J
multiply=: *
Works on arrays of any rank (any number of dimensions): atoms, lists, tables, etc.
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; } }
JavaScript
function multiply(a,b) { return a*b }
Logo
to multiply :x :y output :x * :y end
Lucid
multiply(x,y) = x * y
LSE64
multiply : * multiply. : *. # floating point
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
MAXScript
fn multiply a b = ( a * b )
Modula-3
PROCEDURE Multiply(a, b: INTEGER): INTEGER = BEGIN RETURN a * b; END Multiply;
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
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;
OCaml
let int_multiply = ( * ) let float_multiply = ( *. )
Alternatively,
let int_multiply x y = x * y let float_multiply x y = x *. y
OpenEdge/Progress
function multiply returns dec (a as dec , b as dec ): return a * b . end.
Pascal
function multiply(a,b: real): real; begin multiply := a*b; end;
Perl
sub multiply( $$ ) { $a = shift; $b = shift; return $a * $b; }
PHP
function multiply( $a, $b ) { return $a * $b; }
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;
Pop11
define multiply(a, b); a * b enddefine;
Python
Named function:
<python>
def multiply(a, b): return a * b
</python>
Unnamed function:
<python>
multiply = lambda a, b: a * b
</python>
A callable class - may be useful to allow both simple functions and complex classes to use the same interface: <python>
class Multiplier: callcount = 0 def __init__(self, a=1): self.multiplicand = a def __call__(self, a, b): Multiplier.callcount += 1 return self.multiplicand * a m4 = Multiplier(4) m2 = Multiplier(2) print m4(2), m4(4), m4(12), m2(2), m2(3) ### >>> 4 8 48 4 6
</python>
(This trite example implements a simplistic "curried" multiplication class ... but also keeps track of the total number of times any instance has been called as a function. I can conceive of no useful application for it).
Q
multiply:{[a;b] a*b}
Using it
|multiply[2;3] 6
Raven
define multiply use a, b a b *
Or optional infix:
define multiply use a, b (a * b)
Or skip named vars:
define multiply *
Ruby
def multiply(a, b) a * b end
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;
SNUSP
For expediency, the function is adding two values, instead of multiplying two values. Another function, atoi (+48) is called before printing the result.
+1>++2=@\=>+++3=@\==@\=.=# prints '6' | | \=itoa=@@@+@+++++# \=======!\==!/===?\<# \>+<-/
Tcl
Strictly as described in the task:
proc multiply { arg1 arg2 } { return [expr $arg1 * $arg2] }
But I'm not sure anybody would write it that way. If nothing else, there's no reason to prefer scalar arguments. And it is unclear why one would impose a limit on the number of arguments. I would write it like this:
proc multiply { args } { return [expr [join [join [join $args]] *]] }
This will accept one or more arguments which can be scalars or lists (or even nested lists) and returns the product of all of them. E.g.
% multiply "1 2" {3 4} [list 5 6] {{7 8} 9} => 362880
Toka
[ ( ab-c ) * ] is multiply
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 *].
Visual Basic .NET
Private Integer Function (Can only be used within a Class)
Private Function multiply(ByVal a AS Integer, ByVal b AS Integer) As Integer Return a * b End Function
Public Integer Function (Can be used outside a Class)
Public Function multiply(ByVal a AS Integer, ByVal b AS Integer) As Integer Return a * b End Function
Call the function
multiply(1, 1)
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="product"> <xsl:param name="a" select="2"/> <xsl:param name="b" select="3"/> <fo:block>product = <xsl:value-of select="$a * $b"/></fo:block> </xsl:template>
<xsl:call-template name="product"> <xsl:with-param name="a">4</xsl:with-param> <xsl:with-param name="b">5</xsl:with-param> </xsl:call-template>
<xsl:call-template name="product"/> <-- using default parameters of 2 and 3 -->