Principles of Programming Languages — Homework 1

Due by class time Thursday, September 5

Preliminaries

Four Little Programming Exercises

  1. Write and test the function (sphere-volume radius), which takes a radius value as input and calculates the corresponding volume of a sphere using the symbol pi and the formula below:

    Examples:

      (sphere-volume 1)  →  4.188786666666666
      (sphere-volume 3)  →  113.09723999999999
      (sphere-volume 0)  →  0
    
  2. Write and test the function (absolute-value n), which takes a number n as input and returns its absolute value. You are not allowed to use Scheme's built-in abs function for this problem. Instead, use cond to check if n is less than 0. Examples:

      (absolute-value -3)  →  3
      (absolute-value 3)   →  3
      (absolute-value 0)   →  0
    
  3. Write and test the function (distance x1 y1 x2 y2), which takes four numbers as input, in the order shown, representing the coordinates of two points (x1, y1) and (x2, y2), and computes the distance between the points using the formula below. Hint: The square root function in Scheme is called sqrt.

    Test your function thoroughly. Examples:

      (distance 1 2 4 6)   →  5
      (distance 1 1 2 2)   →  1.4142135623730951
      (distance 4 0 -6 3)  →  10.44030650891055
    
  4. Write and test the function (replace-first new ls), which takes a symbol new and a list of symbols ls as input, and returns a new version of ls with the first symbol replaced by new. If ls is empty to begin with, an empty list is returned as the result. Examples:

      (replace-first 'apple '())  → ()
      (replace-first 'apple '(chocolate sauce yum))  → (apple sauce yum)
      (replace-first 'blue '(green eggs and ham))  → (blue eggs and ham)
      (replace-first 'nobody '(Sam loves green eggs and ham))  → (nobody loves green eggs and ham)
      (replace-first 'margarine '(butter))  → (margarine)
    

Turning in Your Homework