4.12 Arithmetic Operators

  • + right-expr
  • - right-expr
  • left-expr + right-expr
  • left-expr - right-expr
  • left-expr * right-expr
  • left-expr / right-expr
  • left-expr mod right-expr
  • left-expr ^ right-expr

    The arithmetic operators are +, -, *, /, mod, and ^. The meanings (semantics) of those operators generally depend on the types of the operands involved, and they are defined in the various chapters describing the types. However basically the meanings are as follows.

    + denotes the addition, and - the subtraction of additive elements. * is the multiplication of multiplicative elements, / is the multiplication of the left operand with the inverse of the right operand. mod is only defined for integers and rationals and denotes the modulo operation. + and - can also be used as unary operations. The unary + is ignored and unary - is equivalent to multiplication by -1. ^ denotes powering of a multiplicative element if the right operand is an integer, and is also used to denote the action of a group element on a point of a set if the right operand is a group element.

    The precedence of those operators is as follows. The powering operator ^ has the highest precedence, followed by the unary operators + and -, which are followed by the multiplicative operators *, /, and mod, and the additive binary operators + and - have the lowest precedence. That means that the expression -2 ^ -2 * 3 + 1 is interpreted as (-(2 ^ (-2)) * 3) + 1. If in doubt use parentheses to clarify your intention.

    The associativity of the arithmetic operators is as follows. ^ is not associative, i.e., it is illegal to write 2^3^4, use parentheses to clarify whether you mean (2^3)^4 or 2^(3^4). The unary operators + and - are right associative, because they are written to the left of their operands. *, /, mod, +, and - are all left associative, i.e., 1-2-3 is interpreted as (1-2)-3 not as 1-(2-3). Again, if in doubt use parentheses to clarify your intentions.

    The arithmetic operators have higher precedence than the comparison operators (see Comparisons and Membership Test for Collections) and the logical operators (see Operations for Booleans). Thus, for example, a * b = c and d is interpreted, ((a * b) = c) and d.

    gap> 2 * 2 + 9;  # a very simple arithmetic expression
    13
    

    For other arithmetic operations, and for the underlying operations of the operators introduced above, see Arithmetic Operations for Elements.

    [Top] [Previous] [Up] [Next] [Index]

    GAP 4 manual
    February 2000