Search a list of values in a list

Q&A's, tips, howto's
Locked
cameyo
Posts: 183
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

Search a list of values in a list

Post by cameyo »

What is the best method to search for a list of values in a list?
Example:
(set 'pat '(1 4 6))
(set 'lst '(2 2 2 1 4 6 2 2 2 1 4 6 2 2 1))

(ref-lst pat lst) ==> 3 ;the first index
and/or
(ref-all-lst pat lst) ==> (3 9) ;all indexes
Last edited by cameyo on Mon Apr 17, 2023 6:13 pm, edited 1 time in total.

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Search a list of values in a list

Post by ralph.ronnquist »

Code: Select all

(find pat lst (fn (needles item) (member item needles)))
find-all doesn't work for that though

with ref/ref-all:

Code: Select all

(ref pat lst (fn (needles item) (member item needles))))
(ref-all pat lst (fn (needles item) (member item needles)))
It might need "flat" on the ref-all but ref/ref-all also traverses the lst recursively if it's deeper.

EDIT: correction

cameyo
Posts: 183
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

Re: Search a list of values in a list

Post by cameyo »

Thanks Ralph.
But I would like to find the starting index of the sequence 1 4 6, not the single number indices.

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Search a list of values in a list

Post by ralph.ronnquist »

Ah, I misunderstood. That's slightly more convoluted. I suppose one approach could be something like the following:

Code: Select all

(filter (fn (i) (= pat (i (length pat) lst))) (flat (ref-all (pat 0) lst)))

cameyo
Posts: 183
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

Re: Search a list of values in a list

Post by cameyo »

This solves my question.
Thanks again Ralph.
Have a nice day.

Locked