Scheme: Conceptual Solutions

Some problems are marked as malformed list problems, feel free to do them if you read my section on malformed lists, otherwise you should probably skip them.

What would scheme Display?

>>> 17
17
>>> (+ 1 2)
3
>>> ‘(+ 1 2)
(+ 1 2)
>>> (- (+ 3 3) (/ 4 2))
4
>>> (define x 3)
x
>>> (* x x)
9
>>> (define (f x) (if (= x 0) 0 1))
f
>>> (f x)
1
>>> ((lambda (x) (+ x 1)) 7)
8
>>> (((lambda (x) (lambda (y) (+ x y))) 3) 4)
7
>>> (cons 1 2)
(malformed list problem)
(1 . 2)
>>> (cons 3 (cons 4 (cons 5 nil)))
(3 4 5)
>>> (cons 1 (cons 2 (cons 3 4)))
(malformed list problem)
(1 2 3 . 4)
>>> (cons 1 (cons 3 4) (cons 2 nil))
(malformed list problem)
Error
>>> (list 1 (list 2 (list 3 4)))
(1 (2 (3 4)))
>>> (cons 1 (cons (cons 2 (cons 3 4)) (cons (cons 5 (cons 6 nil)) (cons 7 nil))))
(malformed list problem)
(1 (2 3 . 4) (5 6) 7)

Scheme Lists

Draw out box and pointer and write out the cons statement that will produce the following lists (if possible), or prove why the list is not possible.

(6 7 8 9)

(cons 6 (cons 7 (cons 8 (cons 9 nil))))

Screen Shot 2019-01-14 at 11.43.23 AM.png

(8 3 4 7 . 5 6 9) (malformed list problem)

Not possible because there can only be one value after the dot, so there’s nowhere for the 6 and 9 to go.

Screen Shot 2019-01-14 at 11.43.33 AM.png

(8 3 4 7 (5 6 9))

(cons 8 (cons 3 (cons 4 (cons 7 (cons (cons 5 (cons 6 (cons 9 nil))) nil)))))

Screen Shot 2019-01-14 at 11.43.45 AM.png

(5 7 (9 10) (11 12) 13)

(cons 5 (cons 7 (cons (cons 9 (cons 10 nil)) (cons (cons 11 (cons 12 nil)) (cons 13 nil)))))

Screen Shot 2019-01-14 at 11.43.55 AM.png

code writing

Write a function in scheme that will take in a list of numbers and remove all even numbers.
> (define lst '(3 5 2 6 7))
> (odd-only lst)
(3 5 7)
(define (odd-only lst)
    (if (null? lst)
        nil
        (if (even? (car lst))
            (odd-only (cdr lst))
            (cons (car lst) (odd-only (cdr lst))) ) ) )

Write a function in scheme that will take in a list and count the number of times a value (x) appears in it.
> (define lst '(3 7 2 6 7 8 7))
> (x-counter lst 7)
3
(define (x-counter lst x)
    (if (null? lst)
        0
        (if (= (car lst) x)
            (+ 1 (x-counter (cdr lst) x))
            (x-counter (cdr lst) x) ) ) )