Wolfram: Function

By Xah Lee. Date: . Last updated: .

Define Function

Function can be defined by:

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.

Function

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

WolframLang, Define Function