From 687aea533757f03e7a0e9ef69df0a136a0837a83 Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Sat, 5 Mar 2022 12:55:23 +0100 Subject: [PATCH] Type any->01. --- scribblings/utils.scrbl | 10 ++++++++++ utils.rkt | 23 ++++++++++++----------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/scribblings/utils.scrbl b/scribblings/utils.scrbl index 23534ed..de6a67c 100644 --- a/scribblings/utils.scrbl +++ b/scribblings/utils.scrbl @@ -488,3 +488,13 @@ Like @racket[boolean-power], but returns a stream. @examples[#:eval utils-evaluator (stream->list (boolean-power/stream 2)) ]} + +@defproc[(any->01 [x Any]) (U Zero One)]{ + +Converts any non-@racket[#f] value to 1 and @racket[#f] to 0. + +@examples[#:eval utils-evaluator +(any->01 #t) +(any->01 #f) +(any->01 'hello) +]} diff --git a/utils.rkt b/utils.rkt index c71ad62..11eee5b 100644 --- a/utils.rkt +++ b/utils.rkt @@ -25,7 +25,7 @@ update-vertices/unweighted update-graph dotit collect-by-key collect-by-key/sets ht-values/list->set hash->list/ordered multi-split-at lists-transpose in-random cartesian-product-2/stream - cartesian-product/stream boolean-power boolean-power/stream) + cartesian-product/stream boolean-power boolean-power/stream any->01) (define-type Variable Symbol) (define-type (VariableMapping A) (Immutable-HashTable Variable A)) @@ -541,6 +541,15 @@ (module+ test (test-case "boolean-power/stream" (check-equal? (stream->list (boolean-power/stream 2)) '((#f #f) (#f #t) (#t #f) (#t #t))))) + + (: any->01 (-> Any (U Zero One))) + (define (any->01 x) + (if x 1 0)) + + (module+ test + (test-case "any->01" + (check-equal? (any->01 #t) 1) + (check-equal? (any->01 #f) 0))) ) (require 'typed) @@ -552,14 +561,13 @@ update-vertices/unweighted update-graph dotit collect-by-key collect-by-key/sets ht-values/list->set hash->list/ordered multi-split-at lists-transpose in-random cartesian-product-2/stream - cartesian-product/stream boolean-power boolean-power/stream) + cartesian-product/stream boolean-power boolean-power/stream any->01) ;;; Untyped section. (provide ;; Functions - (contract-out [any->01 (-> any/c (or/c 0 1))] - [01->boolean (-> (or/c 0 1) boolean?)]) + (contract-out [01->boolean (-> (or/c 0 1) boolean?)]) ;; Contracts (contract-out [variable-mapping? contract?] [string-variable-mapping? contract?] @@ -584,13 +592,6 @@ ;;; Boolean operations ;;; ================== -;;; Converts any non-#f value to 1 and #f to 0. -(define (any->01 x) (if x 1 0)) - -(module+ test - (test-case "any->01" - (check-equal? (any->01 #t) 1) - (check-equal? (any->01 #f) 0))) ;;; Converts 0 to #f and 1 to #t (define (01->boolean x)