# 2.75

## 练习 2.75 请用消息传递的风格实现构造函数make-from-mag-ang。这一过程应该与上面给出的make-from-real-imag过程类似。

(define (make-from-mag-ang mag ang)
(define (dispatch op)
(cond
((eq? op 'real-part) (* mag (cos ang)))
((eq? op 'imag-part) (* mag (sin ang)))
((eq? op 'magnitude) mag)
((eq? op 'angle) ang)
(else
(error "Unknown op -- MAKE-FROM-MAG-ANG" op)
)
)
)

dispatch
)


=======

## 启发

class ComplexNumber {
constructor(x, y) {
this.x = x;
this.y = y;

this.mag = Math.sqrt(this.x * this.x + this.y * this.y);
this.ang = Math.atan(y, x);
}

static fromMagAng(mag, ang) {
const x = mag * Math.cos(ang);
const y = mag * Math.sin(ang);

const c = new ComplexNumber(x, y);
c.mag = mag;
c.ang = ang;

return c;
}

get realPart() {
return this.x;
}

get imagPart() {
return this.y;
}

get magnitude() {
return this.mag;
}

get angle() {
return this.ang;
}
}

const c = new ComplexNumber(1, 2);
console.log(c.realPart);
console.log(c.imagPart);
console.log(c.magnitude);
console.log(c.angle);



const makeComplexNumberFromRealImag = (x, y) => {
const dispatch = (op) => {
switch (op) {
case 'realPart':
return x;
case 'imagPart':
return y;
case 'magnitude':
return Math.sqrt(x * x + y * y);
case 'angle':
return Math.atan(y / x);
default:
throw new Error('Unknown op: ' + op);
}
}

return dispatch;
};

const n = makeComplexNumberFromRealImag(1, 2);
console.log(n('realPart'));
console.log(n('imagPart'));
console.log(n('magnitude'));
console.log(n('angle'));