The Grinnell Scheme Web:
Useful arithmetic procedures (1)

Now that I know how to define procedures, is it a good idea for me to start creating them?

Sure. You want to build up a procedure library, so that instead of starting over from scratch on each program you write, you can assemble new ones out of familiar components.

How do I know what makes a good procedure? Does every procedure I write belong in a library?

Probably some of the procedures you write will be too specialized to be reused in any other program. Your objective is to minimize the number of such procedures. You want to look for opportunities to break out some potentially recurring subproblem or generalization of the problem to which a particular program is addressed.

A good procedure is one that encapsulates some recurring part or form of a computation. You want to abstract from the idiosyncratic particulars of a program and put into the procedure what is common to all the different instances of a computation.

Another way to identify a good procedure is that you see the same sequence or nesting of calls to the same built-in procedures over and over again. Defining your own procedure to perform the whole sequence will make your programs shorter and often clearer.

Can you give some examples?

The commonest of all arithmetic computations in real-world computer programs is adding one to a number. Some implementations of Scheme predefine a procedure to perform this operation, but the standard does not require it. If your implementation of Scheme does not provide the procedure, you may want to define it -- so that you can easily adapt other programmers' Scheme code that uses it, if for no other reason:

(define (add1 n)
  (+ n 1))
Some other special cases of the arithmetic operators are worth defining:
(define (sub1 n)
  (- n 1))

(define (double n)
  (+ n n))

(define (half n)
  (quotient n 2))         ; remainder is discarded

(define (square n)
  (* n n))

(define (cube n)
  (* n n n))
Here is one common combination of arithmetic operations, shown on a previous page to illustrate the structure of procedure definitions. This procedure computes the magnitude of the difference between two integers (or, indeed, between any two real numbers):
(define (disparity a b)
  (abs (- a b)))


Next topic
Previous topic
Table of contents


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/scheme-web/useful-arithmetic-1.html


created July 23, 1995
last revised May 22, 1996

Copyright 1995, 1996 by John David Stone (stone@math.grin.edu)