Add and use assert-type in utils.

This commit is contained in:
Sergiu Ivanov 2022-04-24 14:34:57 +02:00
parent 2e8373d037
commit 64daec5065
2 changed files with 29 additions and 4 deletions

View file

@ -35,6 +35,28 @@ the variables.
}
@section{Type utilities}
Typed Racket's @racket[cast] should only be used as a last resort, because it
installs two contracts which may have a significant performance penalty.
See
@hyperlink["https://racket.discourse.group/t/managing-cast-performance-penalty/905"]{this
discussion} for more details. The best approach is to use
@hyperlink["https://docs.racket-lang.org/ts-guide/occurrence-typing.html"]{occurrence
typing} either via a direct @racket[if] check using a predicate, or using
@racket[assert].
@defform[(assert-type expr type)]{
@racket[assert] that the type of @racket[expr] is @racket[type].
@examples[#:eval utils-evaluator
(define some-number : Any 1)
(assert-type some-number Integer)
(assert-type some-number Positive-Integer)
(eval:error (assert-type some-number Zero1))
]}
@section{Hashtable injection}
This section defines some utilities to streamline the usage of hash tables

View file

@ -6,6 +6,7 @@
(provide
Variable VariableMapping GeneralPair
assert-type
eval-with eval1-with auto-hash-ref/explicit auto-hash-ref/:
extract-symbols any->string stringify-variable-mapping string->any
handle-org-booleans map-sexp read-org-sexp unorg unstringify-pairs
@ -25,6 +26,9 @@
(define-type Variable Symbol)
(define-type (VariableMapping A) (Immutable-HashTable Variable A))
(define-syntax-parse-rule (assert-type e:expr type:expr)
(assert e (make-predicate type)))
(: eval-with (-> (VariableMapping Any) Any AnyValues))
(define (eval-with ht expr)
(parameterize ([current-namespace (make-base-namespace)])
@ -107,7 +111,7 @@
([x form])
(extract-symbols x)))]
[else '()]))
(assert (extract-rec form) (make-predicate (Listof Symbol))))
(assert-type (extract-rec form) (Listof Symbol)))
(module+ test
(test-case "extract-symbols"
@ -223,7 +227,7 @@
(λ ([pairs : (Listof (Pair Symbol Any))])
(make-immutable-hash pairs))
(λ (sexp)
(assert sexp (make-predicate (Listof (GeneralPair String Any))))
(assert-type sexp (Listof (GeneralPair String Any)))
(unstringify-pairs sexp))
string->any))
@ -244,8 +248,7 @@
(: read-symbol-list (-> String (Listof Symbol)))
(define (read-symbol-list str)
(assert (string->any (string-append "(" str ")"))
(make-predicate (Listof Symbol))))
(assert-type (string->any (string-append "(" str ")")) (Listof Symbol)))
(module+ test
(test-case "read-symbol-list"