Counting elements of a list and sublists

前端 未结 3 928
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 10:37

I\'m trying to create a function to count all the elements in a list, including the elements of its sublists. initially, to get started, i came up with a basic function

3条回答
  •  轮回少年
    2020-12-21 11:13

    Here is a recursive template you can use:

    (define (num-atoms lst)
      (cond ((pair? lst) (+ (num-atoms ) 
                            (num-atoms )))
            ((null? lst) ) ; not an atom
            (else )))      ; an atom
    

    This next example uses a helper that has the accumulated value (num) as an argument.

    (define (num-atoms lst)
      ;; locally defined helper
      (define (helper num lst)
        (cond ((pair? lst) (helper (helper  ) )) ; recurse with the sum of elements from car
              ((null? lst) )          ; return accumulated value
              (else (helper  )))) ; recurse with add1 to num
    
      ;; procedure starts here
      (helper 0 lst))
    

    Hope it helps

提交回复
热议问题