The versatility of using a Map as an index
Posted: Fri Sep 23, 2011 7:24 pm
Ok, this is not earth-shattering. But in the course of investigating the best way to index an ISAM file I found that a Purebasic map is a very good fit. You can enforce no duplicates by using #PB_Map_ElementCheck (the default), necessary for a primary key index, and allow duplicates by using #PB_Map_NoElementCheck. The doc states, rather incorrectly, that if you add a mapkey that already exists in this way, the first element will be kept but will not be anymore searchable. When I read this I feared that a map might not suffice for an index that allows duplicate keys. But some hacking proves otherwise. In a ForEach loop duplicate keys always appear together and once you do a FindElement() on a key of which there are several dupes, NextMapElement() will return the stored values for each instance of the key in the order of newest to oldest. Maps, perfect for both primary key indexes and secondary indexes alike:
As I say, not earth-shattering news but useful information that not everybody will know. I didn't, and the doc is a bit lacking on describing this capability.
Code: Select all
NewMap country.s()
AddMapElement(country(), "Canada", #PB_Map_NoElementCheck)
country() = "1"
AddMapElement(country(), "France", #PB_Map_NoElementCheck)
AddMapElement(country(), "Usa", #PB_Map_NoElementCheck)
AddMapElement(country(), "Canada", #PB_Map_NoElementCheck)
country() = "2"
AddMapElement(country(), "Mexico", #PB_Map_NoElementCheck)
AddMapElement(country(), "Germany", #PB_Map_NoElementCheck)
AddMapElement(country(), "Denmark", #PB_Map_NoElementCheck)
AddMapElement(country(), "Canada", #PB_Map_NoElementCheck)
country() = "3"
AddMapElement(country(), "Mexico", #PB_Map_NoElementCheck)
AddMapElement(country(), "England", #PB_Map_NoElementCheck)
AddMapElement(country(), "Ireland", #PB_Map_NoElementCheck)
AddMapElement(country(), "Scotland", #PB_Map_NoElementCheck)
If FindMapElement(country(),"Canada")
Debug MapKey(country())+" "+country()
result = NextMapElement(country())
While result
If MapKey(country()) = "Canada"
Debug MapKey(country()) + " " + country()
Else
Break
EndIf
result = NextMapElement(country())
Wend
EndIf
Debug ""
ForEach country()
Debug MapKey(country())
Next