Counting elements of a list and sublists

前端 未结 3 930
伪装坚强ぢ
伪装坚强ぢ 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:23

    Make my-length work for any argument type, 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
    

提交回复
热议问题