MODULE C; (* Defines procedures for complex arithmetic. *) (* The procedures in this module represent a complex number as a pair of reals. However, all procedures can accept either reals or pairs of reals as arguments. See also: "R2". *) PROC r := Real(c) IS IF PAIR(c) -> r := CAR(c) | REAL(c) -> r := c FI END; (* Set "r" to the real part of the complex number "c". This is a checked run-time error if "c" is not a real number or a pair. *) PROC i := Imag(c) IS IF PAIR(c) -> i := CDR(c) FI END; (* Set "i" to the imaginary part of the complex number "c". This is a checked run-time error if "c" is not a pair. *) PRIVATE PROC res := ToPair(c) IS IF PAIR(c) -> res := c | REAL(c) -> res := (c, 0) FI END; /* Set "res" to the complex representation of "c", which must be either a real number or a pair. */ PROC res := Plus(c1, c2) IS c1 := ToPair(c1); c2 := ToPair(c2); res := (CAR(c1) + CAR(c2), CDR(c1) + CDR(c2)) END; (* Set "res" to the complex sum of "c1" and "c2". *) PROC res := Times(c1, c2) IS c1 := ToPair(c1); c2 := ToPair(c2); IF VAR a1, b1, a2, b2 IN c1 = (a1, b1) AND c2 = (a2, b2) -> res := (a1 * a2 - b1 * b2, a1 * b2 + b1 * a2) END FI END; (* Set "res" to the complex product of "c1" and "c2". *)