Three Homework Problems
May 3, 2019
All of these are solved by scanning through the list.
- We scan through the linked list to find the spot where the new item belongs, and add it if it is not already present in the list:
(define (adjoin-set x xs) (let loop ((xs xs) (zs (list))) (cond ((null? xs) (reverse (cons x zs))) ((= x (car xs)) (append (reverse zs) xs)) ((< x (car xs)) (append (reverse (cons x zs)) xs)) (else (loop (cdr xs) (cons (car xs) zs))))))
- This is another scan through the input list. Since the list is not necessarily ordered, all we can do is compare equality at each item in the list. We assume the list items are integers, even though the problem did not specify:
(define (list-index x xs) (let loop ((xs xs) (idx 0)) (if (null? xs) -1 (if (= (car xs) x) idx (loop (cdr xs) (+ idx 1))))))
- This is similar to the other two:
(define (update-count k kc-pairs) (let loop ((kc-pairs kc-pairs) (zs (list))) (cond ((null? kc-pairs) (cons (cons k 1) zs)) ((equal? (caar kc-pairs) k) (cons (cons (caar kc-pairs) (+ (cdar kc-pairs) 1)) (append (cdr kc-pairs) zs))) (else (loop (cdr kc-pairs) (cons (car kc-pairs) zs))))))
You can run the program at https://ideone.com/mo77gV.
A Haskell version using direct recursion and no library functions.