Scheme Expression 3. Write a recursive function to count the number of the eleme
ID: 3824753 • Letter: S
Question
Scheme Expression
3. Write a recursive function to count the number of the elements of a list. Please name the function as count-elements. This function should tell how many elements are contained in a list. For example, (count-elements '(a (b c) (d (e) f ))) returns 3.
4. Write a recursive function to count the number of the atoms that appear at all levels of an S-expression. Please name the function as count-atoms. This function should tell how many atoms are contained in a s-expression. For example, (count-atoms '(a (b c) (d (e) f))) returns 6.
5. Write a recursive function to get the maximum number from a sequence of numbers. Please name the function as max. This function should tell the maximum number in a given list.
For example, (max ( 5 6 9 3 6)) will result in 9. 6.
Write a Scheme program for Fibonacci numbers.
The Fibonacci numbers are defined as follows:
Fibonacci(n) = 0 if n = 1
= 1 if n = 2 = Fibonacci(n-1) + Fibonacci(n-2) if n > 2
Explanation / Answer
In recursion,we have cdr-car.
car
returns the first member of a list
cdr
returns the list without its first item, or the second member list
3.
(define (count-elements x)
(cond ((null? x) 0)
(else (+ 1 (length (cdr x))))
)
)
> (count-elements '(a (b c) (d (e) f )))
4.
(define (count-atoms lst)
(cond
((null? lst) 0)
((list? (car lst)) (+ (count-atoms (car lst)) (count-atoms (cdr lst))))
(else (+ 1 (count-atoms (cdr lst))))))
> (count-atoms '(a (b c) (d (e) f)))
6.
(define (fib n)
(if (= n 1)
0
(if (= n 2)
1
(+ (fib (- n 1)) (fib (- n 2))))))
>(fib 4)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.