Skip to content

Instantly share code, notes, and snippets.

@shegeley
Last active May 21, 2024 17:44
Show Gist options
  • Save shegeley/fd90526791bf94f825baa0b3e9f4cf3c to your computer and use it in GitHub Desktop.
Save shegeley/fd90526791bf94f825baa0b3e9f4cf3c to your computer and use it in GitHub Desktop.
Guile Scheme hash table deep hash and equality comparsion
(use-modules (srfi srfi-69))
#|
(hash (list 1 2)) => 1690321764596975924
(hash (list 2 1)) => 1690321764596975924
(hash (vector 1 2)) => 2121270931541232526
(hash (vector 2 1)) => 1271456826911243416
|#
(define (hash-table-deep-hash table)
"Quick and dirty hash-table compare procedure via hashes"
(hash-table-fold table
(lambda (key val acc)
(hash (cond
((hash-table? val)
(cons (hash (vector key (hash-table-deep-hash val))) acc))
(else (cons (hash (vector key val)) acc))))) 0))
(define* (hash-table-compare comparator
#:key (on hash-table-deep-hash)
. args)
(apply comparator (map on args)))
;;; ---------------------------
(define table1
(alist->hash-table
`((nested . ,(alist->hash-table
`((key1 . val1)
(key2 . ,(alist->hash-table
`((key1- . val1-)))))))
(world . hello))))
(define table2
(alist->hash-table
`((world . hello)
(nested . ,(alist->hash-table
`((key2 . ,(alist->hash-table
`((key1- . val1-))))
(key1 . val1)))))))
(hash-table-deep-hash table1) ;; => 435140255619520188
(hash-table-deep-hash table2) ;; => 435140255619520188
(define table3
(alist->hash-table
`((hello . world)
(nested . ,(alist->hash-table
`((key2 . ,(alist->hash-table
`((key1- . val1-))))
(key1 . val1)))))))
(hash-table-deep-hash table3) ;; => 916185344496446167
(define table1
(alist->hash-table
`((nested . ,(alist->hash-table
`((key1 . val1)
(key2 . ,(alist->hash-table
`((key1- . val1-)))))))
(world . hello))))
(define table2
(alist->hash-table
`((world . hello)
(nested . ,(alist->hash-table
`((key2 . ,(alist->hash-table
`((key1- . val1-))))
(key1 . val1)))))))
(hash-table-deep-hash table1) ;; => 435140255619520188
(hash-table-deep-hash table2) ;; => 435140255619520188
(define table3
(alist->hash-table
`((hello . world)
(nested . ,(alist->hash-table
`((key2 . ,(alist->hash-table
`((key1- . val1-))))
(key1 . val1)))))))
(hash-table-deep-hash table3) ;; => 916185344496446167
(hash-table-compare equal? table1) ;; => #t
(hash-table-compare equal? table1 table2 table3) ;; => #f
@shegeley
Copy link
Author

Update: please don't use. It's fundamentally broken. See srfi-125 hash-table?=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment