(* most simple way to define a function *)Function[x, x+1][3]
(* 4 *)(* HHHH------------------------------ *)Clear[myfun]
myfun = Function[x, x+1];
myfun[3]
(* 4 *)(* HHHH------------------------------ *)Clear[myfun]
myfun = Function[{x,y}, x+y];
myfun[3,4]
(* 7 *)(* HHHH------------------------------ *)(* using Function to define a function has a limitation,
on the function parameters.
namely, you can only have ordered param, rest param.
but you cannot have default values, optional param, or named param.
*)(* HHHH------------------------------ *)(* in order to have default values, optional param, or named param.
you need to define function by using pattern matching. *)Clear[myfun];
myfun[x_] := x+1
(* SetDelayed[myfun[Pattern[x, Blank[]]], Plus[x, 1]] *)
myfun[3]
(* 4 *)(* SetDelayed sets a pattern, whenever left-hand-side match, replace it by right-hand-side *)(* the full form is this *)(* HHHH------------------------------ *)(* this is how to show the full form syntax
of some expression *)FullForm[Hold[myfun[x_] := x+1]]
(* HHHH------------------------------ *)(* practical examples of definite a function via pattern matching *)Clear[myfun];
myfun[x_,y_] := x+y
myfun[3,4]
(* 7 *)(* HHHH------------------------------ *)(* example of default vaule *)Clear[myfun];
myfun[x_, y_:4] := x+y
myfun[3]
(* 7 *)(* HHHH------------------------------ *)(* example of 2 default vaules, and
how, you cannot have the first param as optional.
this showcase how
param with default values is not completely equivalent to optional param.
*)Clear[myfun];
myfun[x_:3, y_:4] := x+y
myfun[]
(* 7 *)(* if we want y to be 5, and use default value for x,
this wont work
*)
myfun[,5]
(* HHHH------------------------------ *)(* example of optional named params. *)Clear[ myfun ];
Options[ myfun ] = { x -> 3, y -> 4 };
myfun[OptionsPattern[]] := OptionValue[x] + OptionValue[y]
myfun[]
(* 7 *)Clear[ myfun ];
Options[ myfun ] = { NumberOfPlotPoints -> 30, Color -> Red,
launchMissle -> False
};
myfun[OptionsPattern[]] := OptionValue[myOpt1] + OptionValue[myOpt2]
myfun[]
(* 7 *)