Counting list items and sublist

I am trying to create a function to count all the elements in a list, including the elements of its sublist. first, to get started, I came up with a basic function myList:

(define myLength 
  (lambda (L)
    (cond
      ((null? L) 0)
      (else (+ 1 (myLength (cdr L)))))))

However, this does not help me account for function calls, for example:

(numAtoms '())              "...should be 0"
(numAtoms '(()))            "...should be 0"
(numAtoms '(1 1))           "...should be 2"
(numAtoms '(1 (1 1) 1))     "...should be 4"
(numAtoms '(1 (1 (1 1)) 1)) "...should be 5"

I am trying to use basic functions such as length, null?and list?.

+1
source share
3 answers

, , , , . cons '() :

'()               == '()
'(())             == (cons '() '())
'(1 1)            == (cons 1 (cons 1 '()))
'(1 (1 1) 1)      == (cons 1 (cons 1 (cons 1 '())) (cons 1 '()))
'(1 (1 (1 1)) 1)  == ...

, , cons + '() 0, -, '() 1. :

'()                                         => 0                           == 0
(cons '() '())                              => (+ 0 0)                     == 0
(cons 1 (cons 1 '()))                       => (+ 1 (+ 1 0))               == 2
(cons 1 (cons 1 (cons 1 '())) (cons 1 '())) => (+ 1 (+ 1 (+ 1 0)) (+ 1 0)) == 4
...                                         => ...                         == ...

, - , ! , , , , cons-. , , , :

(define (treeduce pair-fn atom-fn tree)
  (if (pair? tree)
      (pair-fn (treeduce pair-fn atom-fn (car tree))
               (treeduce pair-fn atom-fn (cdr tree)))
      (atom-fn tree)))

cons + 1, 0, :

(define (non-null-atoms tree)
  (treeduce +
            (lambda (atom) 
              (if (not (null? atom))
                  1
                  0))
            tree))

, :

(non-null-atoms '())              ;=> 0
(non-null-atoms '(()))            ;=> 0
(non-null-atoms '(1 1))           ;=> 2
(non-null-atoms '(1 (1 1) 1))     ;=> 4
(non-null-atoms '(1 (1 (1 1)) 1)) ;=> 5
+2

, :

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

(num) .

(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))

,

0

Make it my-lengthwork for any type of argument, list, or atom; then the recursive algorithm becomes almost trivial:

(define (my-length l)
  (cond ((null? l) 0)
        ((list? l) (+ (my-length (car l)) (my-length (cdr l))))
        (else 1)))  ; atom

> (my-length '(1 (1 (1 1)) 1)))
5
0
source

All Articles