Function definition
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
function multiply(a : float; b : float) return float is begin return a * b; end multiply;
ALGOL 68
PROC multiply = ( LONG REAL a, b ) LONG REAL: ( a * b )
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
Forth
: fmultiply ( F: a b -- F: c ) F* ; : multiply ( a b -- c ) * ;
Fortran
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.
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
LSE64
multiply : * multiply. : *. # floating point
MAXScript
fn multiply a b = ( a * b )
OCaml
let int_multiply = ( * ) let float_multiply = ( *. )
Alternatively,
let int_multiply x y = x * y let float_multiply x y = x *. y
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; }
Pop11
define multiply(a, b); a * b enddefine;
Python
Named function:
def multiply(a, b): return a * b
Unnamed function:
multiply = lambda a, b: a * b
A callable - may be useful to allow both simple functions and complex classes to use the same interface:
>>> class Multiply: ... def __call__(self, a, b): ... return a * b ... >>> multiply = Multiply() >>> multiply(3, 4) 12
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