Search code examples
elisp

setq: wrong type argument: listp 1


My group and I are trying to create a list of cons lists. It might look something like this

((2 100032) (4 32413) (6 2131251) ... (232 12))

Unfortunately, we keep getting a "wrong type argument". It might be something simple but I also wonder if we are doing something wrong with cons.

Any responses appreciated:

(defun find-diffs ()
    (let ((diffs (list))
          (index 0)
          (previous 0))
         (while (< index (length first-ten-million-primes))
           ; Add the difference to the list of diffs.
           (setq diff (- (aref first-ten-million-primes index) previous))
           ; We only want to bother recording it if the index is above zero and
           ; the difference is odd.
           (if (and (> index 0) (evenp diff))
             (setq diffs
               ; Can we find this one in our list of diffs?
               (if (cdr (assoc diff diffs))

                 ; Yes
                 ; ERROR happens when we call this statement
                 (setq diffs 
                   (append (cons diff (1+ (car (cdr (assq diff diffs)))))
                           (assq-delete-all diff diffs)))
                 ; No
                 (setq diffs (plist-put diffs diff 1)))))
           ; Set previous value to this one.
           (setq previous (aref first-ten-million-primes index))
           ; Increment the index.
           (setq index (1+ index)))
         diffs)

Commenting out the (setq diffs) will fix it, but I don't see anything wrong with how we are setting our variables.

Thanks!

The backtrace is huge so I will only post the first part. My team is still confused as to what's wrong so any responses appreciated.

Debugger Backtrace:

Debugger entered--Lisp error: (wrong-type-argument listp 1)
  append((2 . 1) nil)
  (setq diffs (append (cons diff 1) diffs))
  (if (cdr (assoc diff diffs)) (setq diffs (append (cons diff (1+ (car (cdr (assq diff diffs)))))

Solution

  • Your problem is in:

                   (append (cons diff (1+ (car (cdr (assq diff diffs)))))
                           (assq-delete-all diff diffs)))
    

    The cons up there create a cell of the form (DIFF . N) which is not a proper list. It's a pair of two element rather than a list of two elements. A list of two elements would have the form (DIFF N) which is a shorthand for (DIFF . (N . nil)).

    I haven't tried to understand what is your overall goal, but there are two ways to fix your problem: Either replace

    (append (cons diff FOO)
            ...)
    

    with

    (append (list diff FOO)
            ...)
    

    or with

    (cons (cons diff FOO)
          ...)