Sample Questions
Each of these questions corresponds to a previous quiz.
Swap Pairs
For this question you will write a racket function swap-pairs
. This
function swaps the first and second elements of each sub-list of the input. The following test illustrates this
functionality
(check-equal? (swap-pairs '((1 2) (3 4) (5 6))) '((2 1) (4 3) (6 5)))
To get a passing mark, you must
- use only functions from
#lang racket
and modulerackunit
. - not use mutation (functions like
set!
ending in!
. - provide a solution that works for lists of arbitrary length.
- Have complete test coverage.
To get full marks you must
- document and test behaviour when given top
level list elements that are not lists of length 2. It's up to you
to decide what the precise behaviour of e.g.
(swap-pairs '(1 2 3))
is, but you should either return a list or callerror
. - use tail recursion to traverse the list.
- use only
match
to access parts of lists. - should not use list functions other than
cons
,list
,reverse
- have well documented tests.
Sixes and Sevens
Code
Write a tail-recursive function
sixes-and-sevens
that keeps all multiples of 6 or
7. It should in particular pass the following test.
(module+ test
(require rackunit)
(check-equal? (sixes-and-sevens '(1 6 7 12)) '(6 7 12)))
Tests
Copy your solution to the previous question and add at least 3 tests
tests for your sixes-and-sevens
function. For full marks you
should test 3 logically different things, and document what you are
testing.
Tree Map
Write a recursive function tree-map
that applies a given function to
each leaf (non-list) element of a list. Your function should pass the
following tests.
(module+ test
(require rackunit)
(check-equal? (tree-map add1 '()) '())
(check-equal? (tree-map add1 '(1 2 3)) '(2 3 4))
(check-equal? (tree-map (lambda (x) (* x x)) '(1 2 3)) '(1 4 9))
(check-equal? (tree-map sub1 '(1 (2 3))) '(0 (1 2)))
(check-equal? (tree-map (lambda (x) (modulo x 2))
'((1 2) (3 4) 5 (6 (7))))
'((1 0) (1 0) 1 (0 (1))))
(check-equal? (tree-map (lambda (x)
(string-append "I wanna " x))
'("pony" ("xbox" "A+")))
'("I wanna pony" ("I wanna xbox" "I wanna A+"))))
List to hash
Write a function that takes a list, and returns an immutable hash table mapping positions (numbered from 1) to elements of the list. For full marks, your function should be tail recursive and pass all of the following tests.
(module+ test
(require rackunit)
(define hash-table (list->hash (list "a" "b" "c")))
(check-equal? (hash-ref hash-table 1) "a")
(check-equal? (hash-ref hash-table 2) "b")
(check-equal? (hash-ref hash-table 3) "c")
(check-equal? hash-table (hash 1 "a" 2 "b" 3 "c")) ;; check entire table, no extra elements
(check-equal? (list->hash (list)) (hash)) ;; handle empty list
(check-equal? (list->hash (list 1 2 3)) (hash 1 1 2 2 3 3)) ;; handle list of numbers
(check-equal? (list->hash (list 1 "b" 'c) ) (hash 1 1 2 "b" 3 'c)))