You must implement three functions from each of the “List,” . In some cases, the
ID: 3604985 • Letter: Y
Question
You must implement three functions from each of the “List,” . In some cases, these functions are already defined in Racket (DrRacket). To avoid confusion, you can name yours differently, for example “myreverse” for “reverse”. Or you can just override the built-in definition. You may use other builtin functions, such as if, cond, car (first), cdr (rest), and cons in your functions. But you may not, of course, use a builtin function in your answer for that same function. (Racket is a type of language in Lisp)
List Functions
You must implement at least three of these list functions.
1. Append two lists (append ’(1 3 x a) ’(4 2 b)) => ’(1 3 x a 4 2 b)
2. Reverse a list (reverse ’(a b c d)) => ’(d c b a)
3. Map a function to every element in a list (define (add3 x) (+ 3 x)) (map add3 ’(1 2 3 4)) => ’(4 5 6 7)
4. Remove duplicates from a list (nub ’(1 1 2 4 1 2 5)) => ’(1 2 4 5)
5. Fold-left (arguments are: initial value, function, list) (fold 10 - ’(1 3 2)) => 4 3
6. Filter (define (lessthan3 x) (< x 3)) (filter lessthan3 ’(1 4 5 2 1 6)) => ’(1 2 1)
7. Merge two sorted lists (merge ’(1 3 4 7) ’(2 3 6)) => ’(1 2 3 3 4 6 7)
8. Add an element to the end of a list. Cool hint: try using reverse (addtoend ’d ’(a b c)) => ’(a b c d)
9. Index of (indexof ’a ’(b c a d)) => 2 (indexof ’a ’(b c d f)) => -1
10. Remove-all (remove-all ’a ’(b a c a a d a)) => ’(b c d)
Explanation / Answer
Scheme:
> (define (myappend l1 l2) (if (null? l1) l2 (cons (car l1) (myappend (cdr l1) l2) ) ))
> (define (myreverse l) (if (null? l) '() (myappend (myreverse (cdr l)) (list (car l) ) )))
> (define (mymap f l) (if (null? l) '() (cons (f (car l)) (mymap f (cdr l) ))))
> (define (addtoend e l) (if (null? l) (list e) (cons (car l) (addtoend e (cdr l)) ) ))
> (define (remove-all e l) (if (null? l) '() (if (equal? e (car l)) (remove-all e (cdr l)) (cons (car l) (remove-all e (cdr l) ) ) )))
> (define (indexof e l) (define (index-Of i e l) (if (null? l) -1 (if (equal? e (car l)) i (index-Of (+ i 1) e (cdr l) ) )) ) (index-Of 0 e l) )
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.