Q&A: Define vector function

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}

[Home] [News] [Homework] [Files] [Exams] [Notes] [Policy] [Links]