From 9175a98a2a1f8defcc3c103422d530eb2ae083de Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Sun, 12 Mar 2023 20:54:25 +0100 Subject: [PATCH] Add hash-replace-keys/ordered. --- scribblings/utils.scrbl | 14 ++++++++++++++ utils.rkt | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/scribblings/utils.scrbl b/scribblings/utils.scrbl index 0dad8ee..d04fc8c 100644 --- a/scribblings/utils.scrbl +++ b/scribblings/utils.scrbl @@ -486,6 +486,20 @@ hash table orders them for @racket[hash-map]. (hash->list/ordered #hash((b . 1) (a . 1))) ]} +@defproc[(hash-replace-keys/ordered [ht (Immutable-HashTable (K1 V))] + [new-keys (Listof K2)]) + (Immutable-HashTable K2 V)]{ + +Replaces the keys in @racket[ht] by the keys in @racket[new-keys]. + +The key-value pairs of the hash table @racket[ht] are processed in the +order produced by @racket[hash-map] with @racket[#:try-order?] set to +@racket[#t]. + +@ex[ +(hash-replace-keys/ordered (hash 'a 1 'b 2) '(x y)) +]} + @defproc[(multi-split-at [lists (Listof (Listof a))] [pos Integer]) (Values (Listof (Listof a)) (Listof (Listof a)))]{ diff --git a/utils.rkt b/utils.rkt index 2180567..8faf33d 100644 --- a/utils.rkt +++ b/utils.rkt @@ -15,7 +15,7 @@ read-org-variable-mapping unorgv read-symbol-list drop-first-last list-sets->list-strings pretty-print-set pretty-print-set-sets update-vertices/unweighted update-graph dotit collect-by-key - collect-by-key/sets ht-values/list->set hash->list/ordered + collect-by-key/sets ht-values/list->set hash->list/ordered hash-replace-keys/ordered multi-split-at lists-transpose append-lists in-random cartesian-product-2/stream cartesian-product/stream boolean-power boolean-power/stream any->01 01->boolean @@ -498,6 +498,19 @@ (check-equal? (hash->list/ordered #hash((b . 1) (a . 1))) '((a . 1) (b . 1))))) +(: hash-replace-keys/ordered (All (K1 K2 V) (-> (Immutable-HashTable K1 V) (Listof K2) + (Immutable-HashTable K2 V)))) +(define (hash-replace-keys/ordered ht new-keys) + (make-immutable-hash (map (λ ([new-k : K2] [pair : (Pairof K1 V)]) + (cons new-k (cdr pair))) + new-keys + (hash->list/ordered ht)))) + +(module+ test + (test-case "hash-replace-keys/ordered" + (check-equal? (hash-replace-keys/ordered (hash 'a 1 'b 2) '(x y)) + '#hash((x . 1) (y . 2))))) + (: multi-split-at (All (a) (-> (Listof (Listof a)) Integer (Values (Listof (Listof a)) (Listof (Listof a)))))) (define (multi-split-at lists pos)