@@ -7,6 +7,7 @@ Types and operations for working with complex numbers.
77The ` Complex ` type is generic over an associated ` RealType ` ; complex numbers
88are represented as two ` RealType ` values, the real and imaginary parts of the
99number.
10+
1011```
1112let z = Complex<Double>(1, 2)
1213let re = z.real
@@ -32,32 +33,42 @@ map them into Swift types by converting pointers.
3233Because the real numbers are a subset of the complex numbers, many
3334languages support arithmetic with mixed real and complex operands.
3435For example, C allows the following:
36+
3537``` c
3638#include < complex.h>
3739double r = 1 ;
3840double complex z = CMPLX(0 , 2 ); // 2i
3941double complex w = r + z; // 1 + 2i
4042```
41- The ` Complex ` type does not provide such mixed operators. There are two
42- reasons for this choice. First, Swift generally avoids mixed-type
43- arithmetic, period. Second, mixed-type arithmetic operators lead to
44- undesirable behavior in common expressions when combined with literal
45- type inference. Consider the following example:
43+
44+ The ` Complex ` type does not provide such mixed operators:
45+
4646``` swift
47- let a: Double = 1
48- let b = 2 * a
47+ let r = 1.0
48+ let z = Complex (imaginary : 2.0 )
49+ let w = r + z // error: binary operator '+' cannot be applied to operands of type 'Double' and 'Complex<Double>'
4950```
50- If we had a heterogeneous ` * ` operator defined, then if there's no prevailing
51- type context (i.e. we aren't in an extension on some type), the expression
52- ` 2*a ` is ambiguous; ` 2 ` could be either a ` Double ` or ` Complex<Double> ` . In
53- a ` Complex ` context, the situation is even worse: ` 2*a ` is inferred to have
54- type ` Complex ` .
55-
56- Therefore, the ` Complex ` type does not have these operators. In order to write
57- the example from C above, you would use an explicit conversion:
51+
52+ In order to write the example from C above in Swift, you have to perform an
53+ explicit conversion:
54+
5855``` swift
59- import ComplexModule
6056let r = 1.0
61- let z = Complex< Double > (0 , 2 )
62- let w = Complex (r) + z
57+ let z = Complex (imaginary : 2.0 )
58+ let w = Complex (r) + z // OK
59+ ```
60+
61+ There are two reasons for this choice. Most importantly, Swift generally avoids
62+ mixed-type arithmetic. Second, if we _ did_ provide such heterogeneous operators,
63+ it would lead to undesirable behavior in common expressions when combined with
64+ literal type inference. Consider the following example:
65+
66+ ``` swift
67+ let a: Double = 1
68+ let b = 2 * a
6369```
70+
71+ ` b ` ought to have type ` Double ` , but if we did have a Complex-by-Real ` * `
72+ operation, ` 2*a ` would either be ambiguous (if there were no type context),
73+ or be inferred to have type ` Complex<Double> ` (if the expression appeared
74+ in the context of an extension defined on ` Compex ` ).
0 commit comments