Assignment 1: Scheme Problems

  1. Write a function rac which accepts a non-empty list and returns the last element of that list. (rac is car spelled backwards.)
  2. Write a function rdc which accepts a non-empty list and returns a list containing all of the elements in the argument except the last. Thus, (rdc '(a b c d)) returns (a b c).
  3. Write a function snoc which accepts an item and a list and returns a new list which is just like the old one, but with the item added at the end. Thus, (snoc 'a '(b c d)) returns (b c d a).
  4. Write a function number-sum which accepts a list and returns the sum of all the numbers in that list, ignoring any elements which are not numbers.
  5. Some games (notably Dungeons & Dragons) use unusual polyhedral dice to generate random numbers. For example, there are 4-sided dice (tetrahedrons) and 20-sided dice (icosahedrons). There is a special notation for specifying various die rolls to be made. "2d8+3" indicates that two 8-sided dice should be rolled, the results added together, and 3 added to this sum. The normal roll of two 6-sided dice, as in Monopoly, would be written "2d6+0".

    Write a function roll which accepts three arguments (the number of dice to roll, the number of sides per die, and the added bonus) and returns the result of the roll. The first example above would be (roll 2 8 3), returning a number between 5 and 19, inclusive.

    To do this, you will need the function random, which takes one argument and returns a random number which is at least 0 and is less than its argument. For example, (random 6) is equally likely to return 0, 1, 2, 3, 4, or 5. The code for random (don't try to understand it yet) is given below.

    ;; Adapted from a version provided by Marc Feeley
    (define random
      (let ((seed 0)
            (a 3141592653)
            (c 2718281829)
            (m (expt 2 35)))
        (lambda (limit)
          (cond
            ((and (exact? limit) (integer? limit))
             (set! seed (modulo (+ (* seed a) c) m))
             (quotient (* seed limit) m))
            (else
             (/ (* limit (random 34359738368))
                34359738368))))))
    
Email a .scm file containing these definitions to me.
Last modified: Tue Jan 20 09:23:19 PST 2004