CS 1101 : Creating Operators


When (and How) Should we Create an Operator?

Create an operator when you have a computation that you might want to perform over different data, or when you have two computations that are the same minus a couple of pieces of data.

For an example of the latter, consider the following expressions that compute the circumference of circles:

   > (* 2 3.14 10)
   > (* 2 3.14 5)

Notice that these two are the same except for the 10 and the 5 (the radius of the circle). We can make an operator for the common expressions by taking the following steps:

  1. Come up with a name for the data that is different (in this case, radius)

  2. Rewrite the expression using that name in place of the different data, copying everything that is the same:
         (* 2 3.14 radius)
    
  3. Wrap the expression in a define that provides both a name for the operator (in this case, circumference) and the name of the different data (in this case, radius):
         (define (circumference radius)
           (* 2 3.14 radius))
    
  4. Add contract and purpose
         ; circumference : number -> number
         ; consumes radius of circle and produces circumference
         (define (circumference radius)
           (* 2 3.14 radius))
    

Now, you can use your new operator as follows:

     > (circumference 10)
     > (circumference 5)

This is what we did in class with the moon-weight example. We started with

     > (* 130 moon-rel-gravity)
     > (* 40 moon-rel-gravity)

We called the weight (what's different) earth-weight and rewrote the expression as

     (* earth-weight moon-rel-gravity)

Then we put that inside a define to give a name to the operator:

     ; moon-weight : number -> number
     ; consume a weight on earth and produce same weight on moon
     (define (moon-weight earth-weight)
        (* earth-weight moon-rel-gravity))

Note that the define line introduces a name for the new operator (moon-weight) and also shows the name that we gave to the different data (earth-weight). You must include whatever name you give to the different data after the name of the operator.


Back to the Lectures page