## Jupyter at Bryn Mawr College

Public notebooks: /services/public/dblank / CS245 Programming Languages / 2014-Fall / Notes

# Assignment #01¶

## by Doug Blank¶

Q1) Write the function mylength

In [ ]:
(define mylength
(lambda (lyst)
(cond
((null? lyst) 0)                       ;; base case
(else (+ 1 (mylength (cdr lyst)))))))  ;; recur


Now we test it:

In [2]:
(mylength '())

Out[2]:
0
In [3]:
(mylength '(0))

Out[3]:
1
In [4]:
(mylength '(1 2 3))

Out[4]:
3
In [5]:
(mylength '(1 2 3 4 5))

Out[5]:
5
In [6]:
(null? (cons 1 2))

Out[6]:
#f
In [7]:
(list? (cons 1 (cons 2 (cons 3 '()))))

Out[7]:
#t
In [8]:
'(1 2 3)

Out[8]:
(1 2 3)
In [9]:
(define mylist?
(lambda (lyst)
(cond
((null? lyst) #t)
((and (not (pair? (cdr lyst)))
(not (null? (cdr lyst)))) #f)
(else (mylist? (cdr lyst))))))

In [10]:
(mylist? '())

Out[10]:
#t
In [ ]:
(mylist?

In [20]:
(mylist? (cons 1 2))

Traceback (most recent call last):
File "stdin", line 1, col 1, in 'mylist?'
File "stdin", line 5, col 12, in 'mylist?'
File "stdin", line 5, col 21, in 'cdr'
File "stdin", line 5, col 21
RunTimeError: cdr called on non-pair 2


In [12]:
(snoc 'a '(x y z))

Out[12]:
(x y z a)
In [13]:
(rac '(x y z))

Out[13]:
z
In [14]:
(define count
(lambda (atom lyst)
(cond
((null? lyst) 0)
((eq? (car lyst) atom) (+ 1 (count atom (cdr lyst))))
(else (count atom (cdr lyst))))))

In [15]:
(count 0 '())

Out[15]:
0
In [16]:
(count 'banana '(apple))

Out[16]:
0
In [17]:
(count 'banana '(apple banana))

Out[17]:
1
In [18]:
(count 'banana '(banana apple banana))

Out[18]:
2
In [20]:
(count 'banana '((banana) apple banana))

Out[20]:
1
In [21]:
(define add
(lambda (m n)
(cond
((= n 0) m)
(else (add (+ m 1) (- n 1))))))

In [24]:
(add 1 1000)

Out[24]:
1001