LcyHle
LcyHle

Reputation: 3

How do to count the number of elements in a list?

So here is my code. It should count the number of elements in a list but instead it prints a zero even though a list contains something.

(defun my-list (listA)
    (setq count 0)
    (loop for i in listA
    if(null i)
        count
    else
    do (setq count(+ count 1))))

Upvotes: 0

Views: 2460

Answers (1)

Sylwester
Sylwester

Reputation: 48745

I see you have tagged functional programming, but the solution you are trying to do is far from functional.

A functional approach would be to have a case analysis. The base case would be a empty list. The answer would be 0. The default case would be the length of the rest of the list plus one. eg. (my-length '(1)) ==> (1+ (my-length '()) ==> (1+ 0) ==> 1

That's it. It works for any length list since (my-length '(1 2 3)) ==> (1+ (1+ (1+ 0))) ==> 3

EDIT

Where is count defined? setq updates an existing binding. Perhaps you should use let to make a local binding. Also in loop you can make variables:

(loop :for count :from 0 
      :for element :in listA
      :finally (return count))

loop actually can count, sum and a whole lot more so this is a better way:

(loop :for element :in listA
      :counting t)

Upvotes: 2

Related Questions