Page 1 of 1
					
				match and list patterns
				Posted: Wed Jul 26, 2006 10:20 pm
				by cormullion
				Another puzzler. How do you insert patterns into 
match?
Code: Select all
(set 'numbers '(1 2 3 4 5 6 7))
(set 'matches 
		(match '(* 5 * ) numbers))
(println matches)
;-> ((1 2 3 4) (6 7))
(set 'n 5)
(set 'matches 
		(match '(* n * ) numbers))
(println matches)
;-> nil
How do I create a list pattern?
 
			 
			
					
				
				Posted: Wed Jul 26, 2006 11:22 pm
				by Dmi
				Code: Select all
> (set 'matches
>            (match (list '* n '*) numbers)) 
((1 2 3 4) (6 7))
 
			 
			
					
				
				Posted: Thu Jul 27, 2006 1:53 am
				by Lutz
				... and here is a second way to do it:
Code: Select all
> (letex (n 5) (match '(* n * ) numbers))
((1 2 3 4) (6 7))
> 
Lutz
 
			 
			
					
				
				Posted: Thu Jul 27, 2006 7:58 am
				by cormullion
				Cool, thanks! In the cold light of the morning it looks more sensible.. ;-)
			 
			
					
				
				Posted: Thu Jul 27, 2006 10:24 am
				by cormullion
				And what about putting a list:
Code: Select all
(set 'numbers '(1 2 3 4 5 6 7)) 
(set 'p '(2 3))
(set 'matches 
      (match (list '* p '*) numbers)) 
want this to return a match but it won't find it unless p is expanded somehow...?
 
			 
			
					
				
				Posted: Thu Jul 27, 2006 12:18 pm
				by HPW
				Do you mean this?
Code: Select all
> (set 'numbers '(1 (2 3) 4 5 6 7))
(1 (2 3) 4 5 6 7)
> (set 'p '(2 3))
(2 3)
> (set 'matches (match (list '* p '*) numbers))
((1) (4 5 6 7))
 
			 
			
					
				
				Posted: Thu Jul 27, 2006 12:23 pm
				by Lutz
				Code: Select all
(letex (p 2 q 3) (match '(* p q *) numbers))
or the method DMI suggested:
Code: Select all
(set 'p 2 'q 3)
(match (list '* p q '*) numbers)
Each spec in the match pattern describes an element of the search list, which could be another list (as in HPWs example) but not a sublist. This is why you have to break up p into p,q.
Lutz
 
			 
			
					
				
				Posted: Thu Jul 27, 2006 1:00 pm
				by cormullion
				Thanks again, guys! Do you ever have one of those days when your brain just doesn't want to understand something no matter how hard you try? I'm having one of those days today... 
HPW's code works when p is a nested list and you want to find that nested list. Lutz' code works when you can specify the elements of list in advance. I want to specify the elements in advance but unnest them...
So all I need to do is to use *flat* to flatten the list stored in p... :-)
It took me too long to realise this. So it must be a time for a holiday!
			 
			
					
				
				Posted: Thu Jul 27, 2006 3:52 pm
				by Lutz
				yes, 'flat' seems to be the best way to go:
Code: Select all
(set 'p '(2 3))
(match (flat (list '* p '*)) numbers)
 ; or this
(letex (p '(2 3)) (match (flat '(* p *)) numbers))
the 'flat' solution is probably the best because it is independend from the number of members in 'p'. It will always work to find a sublist in another list, regardles of the length.
Lutz