Hash join: Difference between revisions

Content added Content deleted
(added ocaml)
Line 183: Line 183:
((2,"Alan"),("Alan","Ghosts"))
((2,"Alan"),("Alan","Ghosts"))
((3,"Glory"),("Glory","Buffy"))
((3,"Glory"),("Glory","Buffy"))
</pre>

=={{header|OCaml}}==
This exploits the fact that Hashtbl implements a hash table that can store multiple values for a key, for an especially simple solution:
<lang ocaml>let hash_join table1 table2 =
let h = Hashtbl.create 42 in
(* hash phase *)
List.iter (fun (_,k as s) ->
Hashtbl.add h k s) table1;
(* join phase *)
List.concat (List.map (fun (k,_ as r) ->
List.map (fun s -> s, r) (Hashtbl.find_all h k)) table2)</lang>
Sample run:
<pre>
# let table1 = [27, "Jonah";
18, "Alan";
28, "Glory";
18, "Popeye";
28, "Alan"];;
# let table2 = ["Jonah", "Whales";
"Jonah", "Spiders";
"Alan", "Ghosts";
"Alan", "Zombies";
"Glory", "Buffy"];;
# hash_join table1 table2;;
- : ((int * string) * (string * string)) list =
[((27, "Jonah"), ("Jonah", "Whales")); ((27, "Jonah"), ("Jonah", "Spiders"));
((28, "Alan"), ("Alan", "Ghosts")); ((18, "Alan"), ("Alan", "Ghosts"));
((28, "Alan"), ("Alan", "Zombies")); ((18, "Alan"), ("Alan", "Zombies"));
((28, "Glory"), ("Glory", "Buffy"))]
</pre>
</pre>