Question. How do I define a function that takes a vector argument?
Answer. There are two basic methods. Itīs usually a matter of taste or style as to which method to use.
Method 1: Use a single named pattern variable on the left of the := to stand for an arbitrary vector. And then on the right of the := perform algebraic operations directly upon tthe named variable or else access the individual coordinates by indexing (using [[ ]] ). For example:
translate[v_] := v + {2, 3} reflect[v_] := {v[[1]], - v[[2]]}
Method 2: Use a list of two pattern variables on the left of the := to stand for an arbitrary (2-dimensional) vector. And then on the right of the := operate upon the list or the individual entries of the list. For example:
translate[{x_, y_}] := {x, y} + {2, 3} reflect[{x_, y_}] := {x, -y}
Note that the argument as shown in Method 2 is a list (with two entries). You could, instead, define the function to take two separate arguments:
translate[x_, y_] := {x, y} + {2, 3} reflect[x_, y_] := {x, -y}
Or, having made the definition that uses the list with two entries, you could simply add the definition:
translate[x_, y_] := translate[{x, y}] reflect[x_, y_] := reflect[{x, y}]
Conversely, if you have already made the definitions that use one-argument list with two entries..
translate[x_, y_] := {x, y} + {2, 3} reflect[x_, y_] := {x, -y}
.. then you could make the definition for two separate arguments by invoking the Sequence function, like this:
translate[x_, y_] := translate[Sequence[{x, y}]] reflect[x_, y_] := reflect[Sequence[{x, y}]]
|