Hash join: Difference between revisions

→‎{{header|TXR}}: Updated code. Works with TXR 76 and up which provides the group-by function.
(→‎{{header|TXR}}: group-by solution.)
(→‎{{header|TXR}}: Updated code. Works with TXR 76 and up which provides the group-by function.)
Line 881:
 
=={{header|TXR}}==
 
Generic hash join. Arguments <code>left-key</code> and <code>right-key</code> are functions applied to the elements of the <code>left</code> and <code>right</code> sequences to retrieve the join key.
 
<lang txr>@(do
Line 888 ⟶ 890:
(18 Popeye)
(28 Alan)))
 
(defvar nemesis-name '((Jonah Whales)
(Jonah Spiders)
Line 893 ⟶ 896:
(Alan Zombies)
(Glory Buffy)))
(defvar name-hash (hash))
 
(defun hash-join (left left-key right right-key)
(each ((tuple age-name)
(let (name(join-hash [mapcargroup-by second ageleft-namekey left])) ;; hash phase
(append-each ((r-entry right)) ;; join phase
(push tuple [name-hash name]))
(collect-each ((l-entry [join-hash [right-key r-entry]]))
'(,age ,namel-entry ,nemesisr-entry)))))
 
(format t "~s\n" [hash-join age-name second nemesis-name first]))
(let ((out (append-each*
((name [mapcar first nemesis-name])
(nemesis [mapcar second nemesis-name])
(hlist [mapcar (op gethash name-hash) name]))
(collect-each
((age [mapcar first hlist]))
'(,age ,name ,nemesis)))))
(format t "~s\n" out)))
</lang>
 
Line 912 ⟶ 909:
 
<pre>$ txr hash-join.txr
((27 Jonah Whales) (27 Jonah Spiders) (28 Alan Ghosts) (18 Alan Ghosts) (28 Alan Zombies) (18 Alan Zombies) (28 Glory Buffy))</pre>
 
Using the unreleased TXR in git, it is be possible to replace the construction of the <code>name-hash</code> with a one liner, eliminating the block of code which walks the tuples and pushes them into buckets based on hashing the name:
 
<lang txr>(defvar name-hash [group-by second age-name])</lang>
 
(((27 Jonah) (Jonah Whales)) ((27 Jonah) (Jonah Spiders)) (28(18 Alan) (Alan Ghosts)) (18(28 Alan) (Alan Ghosts)) (28(18 Alan) (Alan Zombies)) (18(28 Alan) (Alan Zombies)) ((28 Glory) (Glory Buffy)))</pre>
The <code>group-by</code> function, which will be officially released in TXR 76, is inspired by Ruby solution; it seems worth including in the programming language.
543

edits