Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] Re: Finding a value in a series?

From: joel:neely:fedex at: 21-May-2001 11:31

Hi, Charles, Charles Wardell wrote:
> How do you do a find on the first element in a series of blocks? > > >> probe blk > [ > [1 a b] > [2 c d] > [3 e f] > ] > > I want to search for the value 2 and assign the remainder to a > variable. I then want to delete the record in the series? >
My first suggestion is that you not do all of the above at once. I'd address the first issue first (finding a sub-block on a second- level key), then separately munge the result. Since you are wanting to mutate the searched block, you will have to get back a repositioned version of the block. This can be done as follows: locate: func [b [block!] n [integer!]] [ forall b [ if b/1/1 = n [return b] ] ] which behaves as follows:
>> blk
== [ [1 a b] [2 c d] [3 e f] ]
>> locate blk 17
== [ ]
>> locate blk 2
== [ [2 c d] [3 e f] ] In other words, the result of LOCATE is empty if the target key was not found. Otherwise it is positioned so that the sub-block with the target key is in front. A separate function takes the result, copies out the related data and removes the sub-block. extract-data: func [b [block!] n [integer!] /local s d] [ either empty? s: locate b n [ copy [] ][ d: copy next first s remove s d ] ] which behaves as follows:
>> extract-data blk 17
== []
>> extract-data blk 2
== [c d] Just to prove that the 2 entry is gone...
>> blk
== [[1 a b] [3 e f]]
>>
The reason I'd separate out those two functions is the assumption that there would be other situations in which locating a sub-block by the numeric key might be desired. By returning the outer block positioned to the sub-block (or at end, if not found) you can do any of the following: - Change the content in the sub-block - Replace the entire sub-block with a different block - Insert something just in front of the sub-block - Access the content of the sub-block - Remove the sub-block\ Hope this helps! -jn-