Q&A: Set (=) vs. SetDelayed (:=)

Question.  When do I use the equal sign = by itself and when do I use := including the colon?

Answer.  The general rule (to which of course there are exceptions) is:

  • Use Set (=) to assign constant values (including constant vector values) to names.
  • Use SetDelayed (:=) to define functions.

Examples:

    myscalar = 22/3;
    myvect = {2, -5, 3};
    f[x_] := x2
    g[x_, y_] := 2 x - 5 y
    reflect[v_] := {v[[1]], -v[[2]]}
    translate[pt_, t_] := pt + t {2, 3}
    newtriangle[fig_, t_] :=
       image[translate[#, t]&,   fig]

Notice that SetDelayed (:=) typically goes with definitions in which pattern variables (names followed by underscores) are used on the left side of the definitions.

Be sure to type := with no space between the colon and equal sign!  (The two symbols together constitute an abbreviation for the named built-in function SetDelayed.)

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