Example code for counting the elements in "flat lists" and embedded lists
;; (count '((a b) (c (g g)) d)) --> returns 3 ;; (totalcount '((a b) (c (g g)) d)) --> returns 6 ;; ;; The function totalcount goes inside embedded lists to count ;; all the elements in all the lists. ;; The function count only counts the upper most elements. Lists are counted ;; as separate elements. (define (count lis) (if (empty? lis) 0 (+ 1 (count (cdr lis))))) (define (totalcount lis) (cond ((empty? lis) 0) ((not (list? lis)) 1) (else (+ (totalcount (car lis)) (totalcount (cdr lis)))))) ;; (sum '(1 2 3)) --> returns 6 ;; (embeddedsum '(1 2 3)) --> returns 6 ;; (embeddedsum '((3 4) 5 ((4) 3) 1)) --> returns 20 ;; (sum '((3 4) 5 ((4) 3) 1)) --> returns ERROR, this function can't add ;; the list (3 4) to 5, it can't go inside the sublist. Function ;; embeddedsum can go inside sublists to add all the elements. (define (sum lis) () (define (embeddedsum lis) ()
! Object methodsFor: 'algorithms' ! count "(FileStream oldFileNamed: 'countandsum.st') fileIn. #(a b c 2 3 4) count. returns 6" self size = 0 ifTrue: [^0]. ^1 + self allButFirst count. ! embeddedcount "(FileStream oldFileNamed: 'countandsum.st') fileIn. #($a #(b c) #(2 #(3 4))) count returns 3. #($a #(b c) #(2 #(3 4))) embeddedcount returns 6 ." self isCollection ifTrue: [ self size = 0 ifTrue:[^0]. ^(self first) embeddedcount + (self allButFirst) embeddedcount]. ^1. ! sum "(FileStream oldFileNamed: 'countandsum.st') fileIn. #(6 5 3 2 3 4) sum. returns 23" ^self. ! embeddedsum "(FileStream oldFileNamed: 'countandsum.st') fileIn. #(6 #(5 3) #(2 #(3 4))) sum returns ERROR. #(6 #(5 3) #(2 #(3 4))) embeddedcount returns 23." ^self. !
count([],0). count([_|Rest], Answer) :- count(Rest, Temp), Answer is Temp + 1. embeddedcount([],0). embeddedcount([First|Rest], Answer) :- embeddedcount(First, Temp1), embeddedcount(Rest, Temp2), Answer is Temp1 + Temp2. embeddedcount(X,1) :- X \= [], atomic(X). sum([],0). sum([First|Rest], Answer) :- sum(Rest, Temp), Answer is Temp + First. embeddedsum([],0). /* ?-consult(countandsum). ?- embeddedcount([a,c,v],X). X = 3 ?- embeddedcount([a,[c,v]],X). X = 3 ?- embeddedcount([a,[c,v],[[1,2],3],4],X). X = 7 ?- count([a,[c,v],[[1,2],3],4],X). X = 4 ?- sum([2,3,5,7,6,8],X). X = 31 ?- embeddedsum([2,3,5,7,6,8],X). X = 31 ?- embeddedsum([2,[3,5],[[7,6]],8],X). X = 31 */
fun count(L:int list) : int = if L = nil then 0 else 1 + count(tl(L));