On Thu, Oct 21, 2021 at 5:26 AM George Neuner <[email protected]> wrote:

>
> On 10/20/2021 5:53 PM, unlimitedscolobb wrote:
>
>
>
You can get a lot of mileage out of the 'set' datatype, which removes
ordering from the equation, especially since lists will act as sets in a
pinch.  (When you want to improve performance, use 'in-set' and/or
'list->set'.

To see if 2 hashes contain the same set of keys:
>
>     (and (= (hash-count hash1) (hash-count hash2))
>          (for/and ([k (in-list (hash-keys hash1))])
>            (hash-has-key? hash2 k)))
>

Alternatively:

(set=? (hash-keys hash1) (hash-keys hash2))


; Return an unordered list of the keys that are in hash1 but not in hash2
(set-subtract (hash-keys hash1) (hash-keys hash2))

; Get a new hash consisting of the key/values that are in hash1 but not in
hash2
(for/hash ([k (set-subtract (hash-keys hash1) (hash-keys hash2))])
  (values k (hash-ref hash1 k)))

; Get a ore detailed breakdown:
(require handy)
(define hash1 (for/hash ([k '(a b c d e f g)] [v 10]) (values k v)))
(define hash2 (for/hash ([k '(a b c d e z y)] [v 10]) (values k v)))
(define hash3 (hash-set* hash2 'c 111 'd 184))
(disjunction hash1 hash3)
Result:
(dict-disjunction
 '#hash((c . (2 111)) (d . (3 184))); values that differ between the hashes
 '#hash((f . 5) (g . 6)) ; key/values that exist only in hash1
 '#hash((y . 6) (z . 5)) ; key/values that exist only in hash3
 '#hash((a . 0) (b . 1) (c . 2) (d . 3) (e . 4) (f . 5) (g . 6)) ; hash1
 '#hash((a . 0) (b . 1) (c . 111) (d . 3) (e . 4) (y . 6) (z . 5))) ; hash3


> Unfortunately, there is no variant of "for" that creates mutable hashes.
> But the general form works for anything.
>

If you don't mind inefficiency then handy can be, well, handy:

(define imm-h  (for/hash ([k '(a b c)][v 3]) (values k v)))
(immutable? imm-h)
(immutable? (hash->mutable imm-h))

hash->mutable takes an existing hash, which can be either immutable or
mutable, and adds its key/values to a new mutable hash one by one, then
returns that hash.

The handy module is a bit of a Fibber McGee that really needs to be broken
out.  It's thoroughly documented, but unfortunately only in comments.
Converting that to proper scribble is one of my Copious Free Times projects.

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/racket-users/CAE8gKoeZWCPg4yS41L9jPeL7gZzgW1iLusr3xJJYQTsj6491Xg%40mail.gmail.com.

Reply via email to