1

I am trying to learn clisp and I have started learning how to manipulate lists recursively. I am unsure wether it is my logic or if I am just too unfamiliar with the constructs of lisp, for some I am able to do it i.e. for procedure (separate '(a 1 b 2 c 3 d 4)) => ((1 2 3 4) (a b c d)) by doing

(defun separate (lst)
  (if (endp lst)
      '(nil nil)
      (let ((x (separate (cdr lst))))
         (if (numberp (car lst))
             (list (cons (car lst)
                         (car x)))
             (list (car x)
                   (cons (car lst) (cadr x)))))))

but when I do the same approach for another procedure

(greater-than-n '(9 1 8 2 7 3 6 4) 5)

I would expect to get a list : ((9 8 7 6) (1 2 3 4))

but instead I get: ((9 8 7 6))

My program thus far is:

(defun greater-than-n (lst n)
    (if (endp lst)
        '(() ())
        (let ((x (greater-than-n (cdr lst) n)))
             (if (> (car lst) n) 
                 (list (cons (car lst)      
                             (car x)))
                 (list (car x)
                       (cons (car lst) 
                             (car x)))))))

I appreciate any help or comments.

sds
  • 58,617
  • 29
  • 161
  • 278
Romsca Z.
  • 13
  • 3
  • what is `part` function? did you mean `greater-than-n`? – rsm Mar 20 '17 at 17:30
  • yes, sorry, I have corrected it, along with other various mistakes in my question – Romsca Z. Mar 20 '17 at 17:37
  • can you please confirm `(separate '(a 1 b 2 c 3 d 4)) => ((1 2 3 4) (a b c d))` ? i'm on sbcl now, not clisp, but it's also common-lisp, and i get `((1 2 3 4) (A 1 2 3 4))` – rsm Mar 20 '17 at 17:46
  • sorry, I typed (car x) instead of (cadr x) for the last cell – Romsca Z. Mar 20 '17 at 17:55
  • thanks for updating question, but now i get `((1 2 3 4) (A))`, still not `((1 2 3 4) (A B C D))` – rsm Mar 20 '17 at 17:56
  • I have updated the code for separate again, as far as I can tell they are identical but it works on gnu-clisp interpreter, perhaps it has a different implementation than sbcl? – Romsca Z. Mar 20 '17 at 18:17
  • i'm pretty sure your `separate` function still didn't work (as pointed also in the answer provided by @sds). but it's great you figure out how to fix it! :) – rsm Mar 20 '17 at 18:31

1 Answers1

2

Your bug is in the

             (list (cons (car lst)      
                         (car x)))

form: you are returning a list of 1 element.

PS. Your functions seem like a textbook case for using multiple values instead of a list of values.

Community
  • 1
  • 1
sds
  • 58,617
  • 29
  • 161
  • 278