Wolfram: Function
Define Function
Function can be defined in 2 ways: Pure Function and pattern matching.
Define Function as Pure Function by 「Function」
Using Function
.
This is fast and direct.
Function defined this way is called Pure Function.
Pure function is similar to lambda in other languages, e.g. • Elisp: Lambda Function • JS: Arrow Function
Define Function by Pattern Matching
Create a global rule of pattern matching.
This is slower but more powerful. It allows you to define optional parameters, default values, rest parameters, parameters of any tree structure, definition of special cases, recursive sequences. In general, it defines rules for transformation of expressions. (which includes the so-called polymorphism) 〔see Wolfram: Define Function by Pattern〕
Define Pure Function via Function
Function[x, body]
-
same as
Function[{x}, body]
Function[{x}, body]
-
represent a function with one parameter.
🛑 WARNING: you cannot assign values to function's parameter variable in function body.
(* 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 *)
(* in a function, you cannot change the parameter value *) (* this is error *) Function[{x}, x = 3][4] (* if you really want to change param value, create local var *) Function[{x}, Module[{y = 3}, y] ][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〕