0

"Learning" Lisp for school but don't feel I'm learning correctly. I'm trying to write a function to add all the numbers in a list that is composed of lists, numbers, and strings. I'm ignoring the strings and entering the lists. I'm getting quite lost with all the parenthesis...

Im receiving the error Illegal argument in functor position 0

(defun add-all (L)
    (cond
        (
            (null L)
            (0)
        )
        ( 
            (listp (car L) )
            (+ (add-all (car L)) (add-all (cdr L)) )
        )
        (
            (stringp (car L) )
            (+ (add-all (cdr L)) )
        )
        ( 
            t
            (+ (car L) (add-all (cdr L)) )
        )
    )
)

2 Answers 2

3

You are attempting to call the function 0 in the first clause of your cond. ie. (0). This is the fixed code formatted for readability.

(defun add-all (list)
  (cond
    ((null list) 0)
    ((listp (car list)) (+ (add-all (car list)) (add-all (cdr list))))
    ((stringp (car list)) (+ (add-all (cdr list))))
    (t (+ (car list) (add-all (cdr list))))))

May I ask why are you handling strings in the list?

As an extra, I recommend you use a text editor that can format the code and balance the parens for you. Emacs is the best choice. Also this code is more 'scheme'y than lispy. What book are you using to learn lisp if I may ask.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow very easy fix thank you! The problem is for a school class and "handling strings" was just a requirement of the particular problem (yes a little silly). Our textbook is Concepts of Programming Languages (Sebesta) where we are learning lisp for a taste of functional programming.
Nothing wrong with a functional taste, that although not the most common in Lisp, it is used by some, most notably Scott McKay. But what they are teaching is the (recursive) divide and conquer approach to problem solving more than functional programming. In my experience that approach makes hard problems easier to tackle but leads to code that afterwards is hard to understand by skimming. To illustrate the point I've rewritten the code. You'll see that it uses functions that do only one thing and composes them to solve problems. (1/2)
So most likely they are using lisp (and other languages) as a vehicle to teach you (other) concepts. But if that style is all you see of lisp it would probably leave a bad impression of the language (I know I would). If you want to learn lisp in more detail you should check out Practical Common Lisp. (2/2)
1

In the first clause of cond you have:

(
  (null L)
  (0)
)

I think you want:

(
  (null L)
  0
)

... without the parens.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.