How can I search for a list within a list in Lisp

Discussion of Common Lisp
Post Reply
joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

How can I search for a list within a list in Lisp

Post by joeish80829 » Wed Apr 02, 2014 1:36 pm

So far I can't get this to work. I can append a list to a list but when I try and do a find for the
list '(7 7 7) in the list l, it's coming up nil..Can any one help me search for the list '(7 7 7) in l
and if it's found output a t.

Code: Select all

LISP-CV> (defparameter l (list '(nil nil nil) '(nil nil nil)))
L
LISP-CV> (append (list '(7 7 7)) l)
((7 7 7) (NIL NIL NIL) (NIL NIL NIL))
LISP-CV> (find '(7 7 7) l)
NIL

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: How can I search for a list within a list in Lisp

Post by Goheeca » Wed Apr 02, 2014 3:06 pm

First of all append works in functional style manner so it doesn't modify its argument. You mean probably:

Code: Select all

(setf l (append (list '(7 7 7)) l))
Secondly the two lists with sevens won't probably be eq so your find will find nothing. You should use a key argument test:

Code: Select all

(find '(7 7 7) l :test #'equal)
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

Re: How can I search for a list within a list in Lisp

Post by joeish80829 » Wed Apr 02, 2014 3:43 pm

Thank you so much, that worked like a charm. I'd like to ask you one more thing if you don't mind
when i define l as a list as below and try to append 3 variables to it in a list the variables don't get appended as a list they get appended one by one as below. I have set the variables b, g and r to be 1 2 and 3. I would like the output to be ((1 2 3) (NIL NIL NIL) (NIL NIL NIL)) . Can you help me figure out how to do this.

Code: Select all

LISP-CV> (defparameter l (list '(nil nil nil) '(nil nil nil)))
L
LISP-CV> (setf l (append (list b g r) l))
(1 2 3 (NIL NIL NIL) (NIL NIL NIL)) <---- see they got appended one by one, not as a a list

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: How can I search for a list within a list in Lisp

Post by Goheeca » Wed Apr 02, 2014 11:40 pm

It's easy:

Code: Select all

(setf l (append (list (list b g r)) l))
or

Code: Select all

(setf l (cons (list b g r) l))
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

Re: How can I search for a list within a list in Lisp

Post by joeish80829 » Wed Apr 02, 2014 11:59 pm

Thanks alot man! I really appreciate all the help you have given me since I've been on this forum:)

Post Reply