# CS代考 COMP712 Tutorial Extra-1 ans: – cscodehelp代写

COMP712 Tutorial Extra-1 ans:

1. Write a function, find-even, that returns the first even number in a list.

> (find-even ‘(1 2 3 4))
2

> (find-even ‘(1 (3 4) a 9 (2 2) 10))
10

> (find-even ‘(1 (3 4) a 9 (2 2) 11))
nil

(defun find-even (L &optional (x (car L)))
(cond ((null L) nil)
((and (numberp x) (evenp x)) x)
(t (find-even (cdr L)))))

This example shows how you could use &optional to compute something once and use it throughout the function.

2. Write a function, split, which given a list will return a list of two lists, the length of the first is specified as the second argument which is a number greater than zero:

> (split ‘(1 2 3 4) 2)
((1 2) (3 4))

> (split ‘(1 2 3 4 5 6 7) 5)
((1 2 3 4 5) (6 7))

> (split ‘(1 2 3) 4)
((1 2 3) nil)

(defun split (L n &optional first-list)
(cond ((or (zerop n) (null L)) (list (reverse first-list) L))
(t (split (cdr L) (1- n) (cons (car L) first-list)))))

3. Write a function, lotto, that generates six numbers for you. You may use the function, random, that will give you a random number as shown below:

· (random 40) ;return a number <= 40 39 But, beware the function, random, returns 0 – 40 and hence you have to remove zero if generated. Also, you don’t want to include a number that has already been generated. > (lotto)
(3 7 20 40 32 11)

(defun lotto ()
(let* ((a (my-random))
(b (my-random a))
(c (my-random a b))
(d (my-random a b c))
(e (my-random a b c d))
(f (my-random a b c d e)))
(list a b c d e f)))

(defun my-random (&rest existing-num)
(do ((x (random 40) (random 40)))
((and (> x 0) (not (member x existing-num))) x)))

4. Write a function sum-tree which given a binary tree will return the sum of all its leaf nodes:

; the tree as above
> (sum-tree ‘(a (b (c 2 3) (d 2 3)) (e (f 43 (h 1 9)) 30))))
93

(defun sum-tree (L)
(let ((left-tree (second L)) (right-tree (third L)))
(+ (if (numberp left-tree) left-tree (sum-tree left-tree))
(if (numberp right-tree) right-tree (sum-tree right-tree)))))

The solution is quite straightforward – so don’t be deterred by the apparent complexity of the question.

(a )

(b ) (e )

(f )

(h )

(c )

2 3

(d )

2 3

30

43

1 9

(a )
(b )
(e )
(f )
(h )
(c )
2 3
(d )
2 3
30
43
1
9