From f80dc7f28e630cb66361e65a3a07c52b55ef261c Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Sun, 6 Dec 2020 21:59:28 +0100 Subject: [PATCH] utils.rkt: Add map-sexp. --- scribblings/utils.scrbl | 16 +++++++++++++++- utils-untyped.rkt | 1 - utils.rkt | 13 ++++++++++++- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/scribblings/utils.scrbl b/scribblings/utils.scrbl index 74e4252..e54c343 100644 --- a/scribblings/utils.scrbl +++ b/scribblings/utils.scrbl @@ -2,7 +2,8 @@ @(require scribble/example racket/sandbox (for-label racket graph "../utils.rkt" (only-in typed/racket/base - Any AnyValues Listof String))) + Any AnyValues Listof String Sexp Number + cast))) @title[#:tag "utils"]{dds/utils: Various Utilities} @@ -155,6 +156,19 @@ Reads any value from string. (string->any "(or b (not a))") ]} + +@defproc[(map-sexp [func (-> Any Any)] [sexp Any]) Any]{ + +Given a @racket[Sexp], applies the @racket[func] to any object which is not +a list. + +@racket[map-sexp] will not check whether @racket[func] is indeed applicable to +every non-list element of @racket[sexp]. If this is not the case, a contract +violation for func will be generated. + +@examples[#:eval utils-evaluator +(map-sexp (λ (x) (add1 (cast x Number))) '(1 2 (4 10) 3)) +]} @section{Additional graph utilities} @section{Pretty printing} diff --git a/utils-untyped.rkt b/utils-untyped.rkt index 77cb35a..c1413f8 100644 --- a/utils-untyped.rkt +++ b/utils-untyped.rkt @@ -11,7 +11,6 @@ (provide ;; Functions (contract-out [read-org-sexp (-> string? (listof any/c))] - [map-sexp (-> procedure? any/c any/c)] [unorg (-> string? (listof any/c))] [unstringify-pairs (-> (listof (general-pair/c string? any/c)) (listof (general-pair/c symbol? any/c)))] diff --git a/utils.rkt b/utils.rkt index 22ef972..b9c02b8 100644 --- a/utils.rkt +++ b/utils.rkt @@ -5,7 +5,7 @@ (provide Symbol VariableMapping eval-with eval1-with extract-symbols - any->string stringify-variable-mapping string->any + any->string stringify-variable-mapping string->any map-sexp ;; Syntax auto-hash-ref/explicit auto-hash-ref/:) @@ -174,3 +174,14 @@ [("#f") #f] [((? list?)) (map handle-org-booleans datum)] [ (_) datum]) + +(: map-sexp (-> (-> Any Any) Any Any)) +(define (map-sexp func sexp) + (match sexp + [(? list?) (map ((curry map-sexp) func) sexp)] + [datum (func datum)])) + +(module+ test + (test-case "map-sexp" + (check-equal? (map-sexp (λ (x) (add1 (cast x Number))) '(1 2 (4 10) 3)) + '(2 3 (5 11) 4))))