CS 257 (Spring 2006) Homework 4*

  1. Write a function cond->if which takes a cond expression and transforms it into a set of nested if expressions. For example,
    > (cond->if '(cond ((> x y) (- x y)) ((< x y) (- y x)) (else 0)))
    (if (> x y) (- x y) (if (< x y) (- y x) 0))
    >
    
    You may assume that every cond expression has an else part.

  2. The function list? takes an s-expression s as an argument and returns #t if s is a list and #f otherwise. Give a definition for a function list-all? which takes an s-expression s as an argument and returns #t if s is a list and all pairs in s are also lists. Otherwise list-all? returns #f. For example,
    > (list-all? '(1 ((2 3)) (4)))
    #t
    > (list-all? '(1 ((2 . 3)) (4)))
    #f
    >
    
    You may use list to define list-all?.

  3. The definition of a function, foo, is a <tail definition> if it has the following form:

    (define foo (lambda (<symbol>*) <tail wrt foo>))

    where <symbol>* is zero or more symbols and an expression is <tail wrt foo> if it is not an application of foo:

    <contains no foo applications>

    or

    if it is an application of foo to zero or more expressions which contain no applications of foo:

    (foo <contains no foo applications>*)

    or

    if all applications of foo are contained in expressions which are (themselves) tail recursive with respect to foo and which occur in any of the following contexts:

    where <contains no foo applications> is an expression which contains no applications of foo,and <contains no foo applications>* is zero or more expressions which contain no applications of foo.

    Write a function, tail-definition?, which takes an expression, expr, as an argument, and returns #t if the expression is a <tail definition> and #f otherwise. For example:

    > (tail-definition? '(define fact (lambda (x acc) (if (= x 0) acc (fact (- x 1) (* x acc))))))
    #t
    > (tail-definition? '(define fact (lambda (x) (if (= x 0) 1 (* (fact (- x 1)))))))
    #f
    > (tail-definition? '(define member? (lambda (item ls) (and (not (null? ls)) (or (eq? item (car ls)) (member? item (cdr ls)))))))
    #t
    >
    
    Hint: Divide and conquer. Write helper-functions, tail-wrt? and no-applications-of?. Both take a function name, fname, and an expression, expr, as arguments. tail-wrt? returns #t if expr is tail with respect to fname and #f otherwise. no-applications-of? returns #t if there are no applications of fname in expr, and #f otherwise. For example,

    When You Should Hand It In

    The above should be handed in Mon. Feb 27.

    * This webpage is located at http://cs.unm.edu/~williams/cs257/homework4s06.html