In: Computer Science
give an arbitrary list of integers, how many are 3? (in scheme)
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
;; name the function as count that takes a number(3 in our case) and a list of numbers
(define (count x L)
( ;;if the list is null, then return 0 number of occurrences of x
if (null? L)
0
(if (eq? x (car L)) ;; for each number in the list if x is equal to that number,
(+ 1 (count x (cdr L))) ; increase the count
(count x (cdr L))))) ;; finally return the output of total count of x occurences
Ex:
(count 3 (list 1 3 3 0 12 -5) )
==================