diff --git a/default-recommendations/hash-shortcuts-test.rkt b/default-recommendations/hash-shortcuts-test.rkt index d976538..5930a0d 100644 --- a/default-recommendations/hash-shortcuts-test.rkt +++ b/default-recommendations/hash-shortcuts-test.rkt @@ -54,7 +54,7 @@ test: "hash-ref! with non-constant lambda cannot be simplified to hash-ref! with ------------------------------ -test: "hash-ref with hash-set! lambda can be simplified to hash-ref!" +test: "hash-ref with hash-set! can be simplified to hash-ref!" ------------------------------ (define h (make-hash)) (define k 'a) @@ -66,11 +66,19 @@ test: "hash-ref with hash-set! lambda can be simplified to hash-ref!" ------------------------------ (define h (make-hash)) (define k 'a) +(or (hash-ref h k #false) + (let ([v (+ 1 2 3)]) + (hash-set! h k v) + v)) +------------------------------ +------------------------------ +(define h (make-hash)) +(define k 'a) (hash-ref! h k (λ () (+ 1 2 3))) ------------------------------ -test: "hash-ref with hash-set! lambda and literal keys can be simplified to hash-ref!" +test: "hash-ref with hash-set! and literal keys can be simplified to hash-ref!" ------------------------------ (define h (make-hash)) (hash-ref h 'a (λ () @@ -80,6 +88,13 @@ test: "hash-ref with hash-set! lambda and literal keys can be simplified to hash ------------------------------ ------------------------------ (define h (make-hash)) +(or (hash-ref h 'a #false) + (let ([v (+ 1 2 3)]) + (hash-set! h 'a v) + v)) +------------------------------ +------------------------------ +(define h (make-hash)) (hash-ref! h 'a (λ () (+ 1 2 3))) ------------------------------ diff --git a/default-recommendations/hash-shortcuts.rkt b/default-recommendations/hash-shortcuts.rkt index fa41c0f..972f6e7 100644 --- a/default-recommendations/hash-shortcuts.rkt +++ b/default-recommendations/hash-shortcuts.rkt @@ -82,6 +82,20 @@ (hash-ref! h1 k1 v1)]) +(define-refactoring-rule or-hash-ref-set!-to-hash-ref! + #:description "This expression can be replaced with a simpler, equivalent `hash-ref!` expression." + #:literals (or hash-ref hash-set! let) + [(or (hash-ref h1:id k1:pure-expression #false) + (let ([v1:id initializer:value-initializer]) + (hash-set! h2:id k2:pure-expression v2:id) + v3:id)) + #:when (free-identifier=? #'h1 #'h2) + #:when (syntax-free-identifier=? #'k1 #'k2) + #:when (free-identifier=? #'v1 #'v2) + #:when (free-identifier=? #'v1 #'v3) + (hash-ref! h1 k1 initializer.failure-result-form)]) + + (define-refactoring-rule hash-set!-ref-to-hash-update! #:description "This expression can be replaced with a simpler, equivalent `hash-update!` expression." @@ -124,4 +138,5 @@ hash-ref-set!-with-constant-to-hash-ref! hash-ref-with-constant-lambda-to-hash-ref-without-lambda hash-ref!-with-constant-lambda-to-hash-ref!-without-lambda - hash-set!-ref-to-hash-update!))) + hash-set!-ref-to-hash-update! + or-hash-ref-set!-to-hash-ref!)))