In order to show how abstractions with data can be built, we're going to go through making a complex number package. A complex number is one that has 2 parts, a real part, and an imaginary part. They are often written in one of two ways, in rectangular form:
And in polar form:
Now, we can can do all of the usual arithmetic with complex numbers, addition, subtraction, multiplication and division. There are simple formulae for this;
Addition:
Subtraction:
Multiplication:
Division:
Note how multiplication and division are best expressed in polar form, while addition and subtraction are best expressed in rectangular form. This raises an interesting question: How does one best go about computing these? Do we have one internal representation? If so, which do we choose? There are a large amount of questions. These can be answered by trying to implement a new type of data: the complex number type.
Firstly, we shall create a generic 'Typed' variable:
(definetyped-variable(lambda(typevalue)(cons'Typed(listtypevalue))))
We now need a way to tell if a given variable has a type:
(definetyped?(lambda(var)(and(list?var)(='Typed(carvar)))))
Now, we've introduced two important concepts here, a 'Predicate' and a 'Constructor'. The first is a construct to find if some data is of the correct form, and the second is a procedure that builds our data structure for us.
We must have a way of extracting our data (in this case, the type) from this structure, a way of 'selecting' it:
(definetype-of(lambda(var)(if(typed?var)(car(cdrvar))))
Using this typed value, we can go on to form a more detailed data structure for out complex number:
(definecomplex-rect(lambda(ab)(typed-variable'Rect-Complex(listab))))
Now let's continue, and create acomplex-polar:
(definecomplex-polar(lambda(rthet)(typed-variable'Polar-Complex(listrthet))))
(definecomplex(lambda(typefirst-varsecond-var)(if(equal?'typePolar)(cons(complex-polarfirst-varsecond-var)(complex-rect(sqrt(+(exptfirst-var2)(exptsecond-var2)))0));; Change second half to be the calculated values.(cons(complex-polar00)(complex-rectfirst-varsecond-var)))))
We have our constructors, now we need our predicates:
(defineis-complex?(lambda(var)(and(typed?(carvar))(or(='Rect-Complex(type-of(carvar)))(='Polar-Complex(type-of(carvar)))))))
Now we can define our arithmetic in terms of these procedures.