Exercises for Lesson 3
Exercise 1: list-length
Write a function list-length that computes the length of a list. Here are some example inputs and expected outputs:
(list-length '(1 2 3)) ; 3
(list-length '()) ; 0
(list-length '(a (b c) d)) ; 3For simplicity, you can assume the input is a list, not a number or anything else. Make sure you can do this without using the built-in function length.
Exercise 2: nth
Write a function nth that gets the nth item in a list. You should assume we start counting at 1. Here are some example inputs and expected outputs:
(nth '(a b c d) 3) ; c
(nth '(a b (c d) e) 3) ; (c d)
(nth '(a b (c d) e) -1) ; #f
(nth '(a b (c d) e) 8) ; #fYou can assume the first input is a list, not a number or anything else. If the index to look for is longer than the length of the list or less than 1, return #f.
Exercise 3: Reading Scheme, part 1
Read through the following Scheme procedure.
(define foo
(lambda (lst elt)
(if (null? lst)
(cons elt '())
(cons (car lst)
(foo (cdr lst) elt)))))What would be a good name for this function? To figure this out, try to trace what would happen if we executed (foo '(3 1 4 1 5) 9).
Exercise 4: Reading Scheme, part 2
Read through the following Scheme procedure.
(define bar
(lambda (lst item other)
(cond
((null? lst)
'())
((equal? (car lst) item)
(cons other
(bar (cdr lst) item other)))
(else
(cons (car lst)
(bar (cdr lst) item other))))))What would be a good name for this function? To figure this out, try to trace what would happen if we executed (bar '(3 1 4 1 5) 1 'x).
Exercise 5: remove-first
Write a function remove-first that returns a list with the same items as the original except that the first occurrence of a particular item is no longer there. Here are some example inputs and expected outputs:
(remove-first '(a b c d) 'a) ; (b c d)
(remove-first '(a b a b a) 'a) ; (b a b a)
(remove-first '(a b c d) 'e) ; (a b c d)
Exercise 6: remove-all
Write a function remove-all that returns a list with the same items as the original except that all occurrences of a particular item is no longer there. Here are some example inputs and expected outputs:
(remove-all '(a b c d) 'a) ; (b c d)
(remove-all '(a b a b a) 'a) ; (b b)
(remove-all '(a b c d) 'e) ; (a b c d)Hint: You should be able to do this by making only very small changes to your remove-first code, so start by copy-pasting that!
Exercise 7: cons-each
Write a function cons-each that takes a list of lists and returns a list with a given element consed onto each sublist from the original. Here are some example inputs and expected outputs:
(cons-each '(() (a) (b c)) 'X) ; ((X) (X a) (X b c))
(cons-each '((a b) () (c)) 4) ; ((4 a b) (4) (4 c))
(cons-each '(() () ()) 1) ; ((1) (1) (1))