开发者

let me know the error in the code and edit it

开发者 https://www.devze.com 2023-02-13 02:58 出处:网络
Define a function called symcount that takes a symbol and a list and returns the number of times the symbol occurs in the list. If the list contains sublists, all occurrences should be counted no matt

Define a function called symcount that takes a symbol and a list and returns the number of times the symbol occurs in the list. If the list contains sublists, all occurrences should be counted no matter how deeply they are nested.

(define syscount(lambda (n x)
  (if (empty? x)
    0
  (if (equal? n (car x))
    (+ 1 syscount(n (cdr x)))))))开发者_如何转开发 

this is what i have written help me pls


(define (syscount n x) 
            (if (null? x) 0 
                  (if (list? (car x))  (+ (syscount n (car x)) (syscount n (cdr x))) 
                         (+ (syscount n (cdr x)) (if (equal? n (car x)) 1 0))))) 

Output is

(syscount '1 '(1 2 3))
1
(syscount '1 '(1 (1 2) 3))
2
(syscount '1 '(1 (1 2) 1 (1) 3))
4


Something like:

(define (my-flatten xs)
  (foldr
   (lambda(x acc)
     (if (list? x)
         (append (my-flatten x) acc)
         (cons x acc)))
   (list)
   xs))

(define (my-filter pred xs)
  (let recur ((xs xs)
              (acc (list)))
    (if (empty? xs)
        (reverse acc)
        (if (pred (car xs))
            (recur (cdr xs) (cons (car xs) acc))
            (recur (cdr xs) acc)))))

(define (count-occur s ls)
  (let ((flatten-ls (my-flatten ls)))
    (foldl (lambda (e acc) (if (eq? s e)
                               (+ acc 1)
                               acc))
           0
           flatten-ls)))

Test:

> (count-occur 'foo (list 1 'foo (list 2 'foo 3 'bar) 4 (list 5 (list 6 'foo)) 7 'foo 8))
4


(define (symcount n x)
  (cond((null? x) 0)
       ((list? (car x))(symcount n (car x)))
       ((eq? n (car x))(+ 1 (symcount n (cdr x))))
       (else(symcount n (cdr x)))))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号