We have the next dayatype:
datatype complex = Rec of real * real | Polar of real * real;
and two functions:
- val real =
fn (Rec(x,y) ) => x
| (Polar(r,a)) => r * Math.cos(a);
val real = fn : complex -> real
- val imaginary =
fn (Rec(x,y) ) => y
| (Polar(r,a)) => r * Math.sin(a);
val imaginary = fn : complex -> real
Now, the book defined another function:
- val add_complex =
fn (Rec(x, y), Rec(x', y')) => ( Rec( x + x', y + y') )
| (Rec(x,y), z) => ( Rec( x + real(z), y + imaginary(z) ) )
| (z, Rec(x, y)) => ( Rec( real(z) + x, imaginary(z) + y) )
| (z,z') => (Rec( real(z) + real(z'), imaginary(z) + imaginary(z') ) );
val add_complex = fn : complex * complex -> complex
I didn’t understand what is the z in the function add_complex.
-
Is it the Polar (meaning, I can write Z=polar(a,b)? If it is, so how the complier know it? meaning – Is it get a z, and parse it to polar variable?
-
If it is not polar, So what it can be?
In your code, both
zandz'arePolarbecause the first case covers all of the possibilities in which both areRec, so in the second casezis notRec, or it would have used the first case. Similarly in the other cases, eachzandz'must bePolarbecause otherwise it would have been caught by a previous case instead. Thus you can safely writez=Polar(a,b), or more accuratelyz=Polar(r, a)for radius and angle.