Hash join: Difference between revisions
Content added Content deleted
(take out of draft status) |
(→Tcl: Added implementation) |
||
Line 197: | Line 197: | ||
[[2, "Alan"], ["Alan", "Zombies"]] |
[[2, "Alan"], ["Alan", "Zombies"]] |
||
[[3, "Glory"], ["Glory", "Buffy"]]</pre> |
[[3, "Glory"], ["Glory", "Buffy"]]</pre> |
||
=={{header|Tcl}}== |
|||
<lang tcl>package require Tcl 8.6 |
|||
proc joinTables {tableA indexA tableB indexB} { |
|||
# Optimisation: if the first table is longer, do in reverse order |
|||
if {[llength $tableB] < [llength $tableA]} { |
|||
return [lmap pair [joinTables $tableB $indexB $tableA $indexA] { |
|||
lreverse $pair |
|||
}] |
|||
} |
|||
foreach value $tableA { |
|||
set hashmap([lindex $value $indexA]) $value |
|||
} |
|||
lmap value $tableB { |
|||
set key [lindex $value $indexB] |
|||
if {![info exist hashmap($key)]} continue |
|||
list $hashmap($key) $value |
|||
} |
|||
} |
|||
set tableA { |
|||
{27 "Jonah"} {18 "Alan"} {28 "Glory"} {18 "Popeye"} {28 "Alan"} |
|||
} |
|||
set tableB { |
|||
{"Jonah" "Whales"} {"Jonah" "Spiders"} {"Alan" "Ghosts"} {"Alan" "Zombies"} |
|||
{"Glory" "Buffy"} |
|||
} |
|||
set joined [joinTables $tableA 1 $tableB 0] |
|||
foreach row $joined { |
|||
puts $row |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
{27 "Jonah"} {"Jonah" "Whales"} |
|||
{27 "Jonah"} {"Jonah" "Spiders"} |
|||
{28 "Alan"} {"Alan" "Ghosts"} |
|||
{28 "Alan"} {"Alan" "Zombies"} |
|||
{28 "Glory"} {"Glory" "Buffy"} |
|||
</pre> |