WolframLang: Define Function
Define Function
Function can be defined by:
- Using
Function
. This is fast and direct. (this is similar to Lisp Lambda and JavaScript Arrow Function ) - Create a global rule of pattern matching. This is slower but much more powerful. 〔see WolframLang: Define Function by Pattern〕
Function[x, body]
-
same as
Function[{x}, body]
Function[{x}, body]
-
represent a function with one parameter.
(* a function that adds one. applied to 3 *) Function[ {x}, x + 1 ][3] === 4 (* give the function a name *) f = Function[ {x}, x + 1 ]; f[3] === 4
Function[{x1, x2, etc}, body]
-
- represent a function with formal parameters x1, x2 etc.
- When the function is called, body is evaluated, with formal parameters replaced by arguments.
f = Function[ {x,y}, x + y ]; f[3, 4] === 7
Named Parameters, Default Values, Polymorphism
If you want function to have named parameters, default param values, or polymorphism (meaning, the function behaves differently depending on number of args or their type) , you need to define the function by pattern matching. 〔see Define Function by Pattern〕