github.com/sunvim/utils@v0.1.0/examples/paricia/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "github.com/sunvim/utils/patricia" 7 ) 8 9 func main() { 10 // Create a new tree. 11 trie := patricia.NewTrie() 12 13 // Insert some items. 14 trie.Insert(patricia.Prefix("Pepa Novak"), 1) 15 trie.Insert(patricia.Prefix("Pepa Sindelar"), 2) 16 trie.Insert(patricia.Prefix("Karel Macha"), 3) 17 trie.Insert(patricia.Prefix("Karel Hynek Macha"), 4) 18 19 // Just check if some things are present in the tree. 20 key := patricia.Prefix("Pepa Novak") 21 fmt.Printf("%q present? %v\n", key, trie.Match(key)) 22 key = patricia.Prefix("Karel") 23 fmt.Printf("Anybody called %q here? %v\n", key, trie.MatchSubtree(key)) 24 25 // Walk the tree. 26 trie.Visit(printItem) 27 // "Karel Hynek Macha": 4 28 // "Karel Macha": 3 29 // "Pepa Novak": 1 30 // "Pepa Sindelar": 2 31 32 // Walk a subtree. 33 trie.VisitSubtree(patricia.Prefix("Pepa"), printItem) 34 // "Pepa Novak": 1 35 // "Pepa Sindelar": 2 36 37 // Modify an item, then fetch it from the tree. 38 trie.Set(patricia.Prefix("Karel Hynek Macha"), 10) 39 key = patricia.Prefix("Karel Hynek Macha") 40 fmt.Printf("%q: %v\n", key, trie.Get(key)) 41 // "Karel Hynek Macha": 10 42 43 // Walk prefixes. 44 prefix := patricia.Prefix("Karel Hynek Macha je kouzelnik") 45 trie.VisitPrefixes(prefix, printItem) 46 // "Karel Hynek Macha": 10 47 48 // Delete some items. 49 trie.Delete(patricia.Prefix("Pepa Novak")) 50 trie.Delete(patricia.Prefix("Karel Macha")) 51 52 // Walk again. 53 trie.Visit(printItem) 54 // "Karel Hynek Macha": 10 55 // "Pepa Sindelar": 2 56 57 // Delete a subtree. 58 trie.DeleteSubtree(patricia.Prefix("Pepa")) 59 60 // Print what is left. 61 trie.Visit(printItem) 62 // "Karel Hynek Macha": 10 63 64 } 65 66 func printItem(prefix patricia.Prefix, item patricia.Item) error { 67 fmt.Printf("%s %v\n", prefix, item) 68 return nil 69 }