From 2e8373d037627d83e856ab998833c47874bb3f6a Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Sun, 24 Apr 2022 14:03:27 +0200 Subject: [PATCH] utils: Replace all casts with asserts. https://racket.discourse.group/t/managing-cast-performance-penalty/905 --- utils.rkt | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/utils.rkt b/utils.rkt index 9d2545f..1b9b9bf 100644 --- a/utils.rkt +++ b/utils.rkt @@ -107,7 +107,7 @@ ([x form]) (extract-symbols x)))] [else '()])) - (cast (extract-rec form) (Listof Symbol))) + (assert (extract-rec form) (make-predicate (Listof Symbol)))) (module+ test (test-case "extract-symbols" @@ -173,7 +173,10 @@ (module+ test (test-case "map-sexp" - (check-equal? (map-sexp (λ (x) (add1 (cast x Number))) '(1 2 (4 10) 3)) + (check-equal? (map-sexp (λ (x) + (assert x number?) + (add1 x)) + '(1 2 (4 10) 3)) '(2 3 (5 11) 4)))) (: read-org-sexp (-> String Any)) @@ -220,7 +223,8 @@ (λ ([pairs : (Listof (Pair Symbol Any))]) (make-immutable-hash pairs)) (λ (sexp) - (unstringify-pairs (cast sexp (Listof (GeneralPair String Any))))) + (assert sexp (make-predicate (Listof (GeneralPair String Any)))) + (unstringify-pairs sexp)) string->any)) ;;; A synonym for read-org-variable-mapping. @@ -240,7 +244,8 @@ (: read-symbol-list (-> String (Listof Symbol))) (define (read-symbol-list str) - (cast (string->any (string-append "(" str ")")) (Listof Symbol))) + (assert (string->any (string-append "(" str ")")) + (make-predicate (Listof Symbol)))) (module+ test (test-case "read-symbol-list" @@ -297,7 +302,8 @@ (define gr1 (directed-graph '((a b) (b c)))) (define gr2 (undirected-graph '((a b) (b c)))) (define (dbl [x : Any]) - (define x-str (symbol->string (cast x Symbol))) + (assert x symbol?) + (define x-str (symbol->string x)) (string->symbol (string-append x-str x-str))) (define new-gr1 (update-vertices/unweighted gr1 dbl)) (define new-gr2 (update-vertices/unweighted gr2 dbl)) @@ -336,14 +342,17 @@ (define gr1 (directed-graph '((a b) (b c)))) (define gr2 (undirected-graph '((a b) (b c)))) (define (dbl [x : Any]) - (define x-str (symbol->string (cast x Symbol))) + (assert x symbol?) + (define x-str (symbol->string x)) (string->symbol (string-append x-str x-str))) (define new-gr1-ug (update-graph gr1 #:v-func dbl)) (define new-gr2-ug (update-graph gr2 #:v-func dbl)) (define gr3 (weighted-graph/directed '((10 a b) (11 b c)))) (define new-gr3 (update-graph gr3 #:v-func dbl - #:e-func (λ (x) (* 2 (cast x Number))))) + #:e-func (λ (x) + (assert x number?) + (* 2 x)))) (check-false (has-vertex? new-gr1-ug 'a)) (check-true (has-vertex? new-gr1-ug 'aa))