MrHappyAsthma
MrHappyAsthma

Reputation: 6522

Scheme Function to Count Atomic Elements in a List

I am trying to write a simple recursive definition in Scheme (LISP).

The goal is to count the number of atomic elements in a list and recursively count internal list atoms as well.

For example:

(num_items '((a b) c d))

should return:

4

because "a", "b", "c", and "d" are the four atomic elements in the lists/sub-lists.

My code so far is as follows:

(define (num_items X)
(cond 
    ((null? X) 0)
    (list? (car X) (+ (num_items(car X)) (num_items(cdr X))))
    (else (+ 1 (num_items(cdr X))))
))

(display(num_items '((a b) c d)))

The error is thrown on the 4th line:

(list? (car X) (+ (num_items(car X)) (num_items(cdr X))))

As far as I can tell, the (num_items(car X)) recursion in the addition seems to be causing the error. If I replace that part of the line with a 1 for example to get:

(list? (car X) (+ 1 (num_items(cdr X))))

Then the code compiles and runs, but then it doesn't solve the problem.

I am using Compile Online to test/run my code. The error it throws is:

$gosh main.scheme

gosh: "error": pair required, but got a

Upvotes: 1

Views: 3288

Answers (1)

Óscar López
Óscar López

Reputation: 236170

A pair of parentheses are missing in the fourth line, try this:

(define (num_items X)
  (cond 
    ((null? X) 0)
    ((list? (car X)) (+ (num_items (car X)) (num_items (cdr X))))
    (else (+ 1 (num_items (cdr X))))))

Other than that, the code is fine. Just a minor suggestion: don't close parentheses in a separate line, close them all at the end. Also, notice that you can replace list? with pair? (or cons?, depending on which one is available in your interpreter). This is cheaper than testing if the value is a list.

Upvotes: 2

Related Questions