开发者

ML - datatype and functions

开发者 https://www.devze.com 2023-03-15 04:57 出处:网络
We have the next dayatype: datatype complex = Rec of real * real | Polar of real * real; and two functions:

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.

  1. 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?

  2. If it is not polar, So what it can be?


In your code, both z and z' are Polar because the first case covers all of the possibilities in which both are Rec, so in the second case z is not Rec, or it would have used the first case. Similarly in the other cases, each z and z' must be Polar because otherwise it would have been caught by a previous case instead. Thus you can safely write z=Polar(a,b), or more accurately z=Polar(r, a) for radius and angle.

0

精彩评论

暂无评论...
验证码 换一张
取 消