From 071566b1e15d06051e309555dd7d694a2181f43a Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Wed, 1 Nov 2023 17:13:36 +0100 Subject: [PATCH] Simplify text reader by reusing Racket's float parser --- .../racket/preserves/preserves/read-text.rkt | 44 ++++--------------- 1 file changed, 8 insertions(+), 36 deletions(-) diff --git a/implementations/racket/preserves/preserves/read-text.rkt b/implementations/racket/preserves/preserves/read-text.rkt index 4e8ad72..5fba960 100644 --- a/implementations/racket/preserves/preserves/read-text.rkt +++ b/implementations/racket/preserves/preserves/read-text.rkt @@ -317,49 +317,21 @@ (define (read-raw-symbol-or-number acc) (if (delimiter-follows?) - (let ((input (reverse acc))) + (let ((input (list->string (reverse acc)))) (or (analyze-number input) - (string->symbol (list->string input)))) + (string->symbol input))) (read-raw-symbol-or-number (cons (read-char in-port) acc)))) (define (analyze-number input) (match input - [(cons (and sign (or #\+ #\-)) input) (read-digit+ (list sign) read-fracexp input)] - [_ (read-digit+ (list) read-fracexp input)])) - - (define (read-digit* acc-rev k input) - (match input - [(cons (? char? (? char-numeric? d)) input) (read-digit* (cons d acc-rev) k input)] - [_ (k acc-rev input)])) - - (define (read-digit+ acc-rev k input) - (match input - [(cons (? char? (? char-numeric? d)) input) (read-digit* (cons d acc-rev) k input)] + [(pregexp #px"^([-+]?\\d+)(((\\.\\d+([eE][-+]?\\d+)?)|([eE][-+]?\\d+))([fF]?))?$" + (list _ whole _ frac _ _ _ f)) + (define n (string->number (if frac (string-append whole frac) whole))) + (cond [(not n) #f] + [(and f (positive? (string-length f))) (float n)] + [else n])] [_ #f])) - (define (read-fracexp acc-rev input) - (match input - [(cons #\. input) (read-digit+ (cons #\. acc-rev) read-exp input)] - [_ (read-exp acc-rev input)])) - - (define (read-exp acc-rev input) - (match input - [(cons (and e (or #\e #\E)) input) (read-sign-and-exp (cons e acc-rev) input)] - [_ (finish-number acc-rev input)])) - - (define (read-sign-and-exp acc-rev input) - (match input - [(cons (and sign (or #\+ #\-)) input) (read-digit+ (cons sign acc-rev) finish-number input)] - [_ (read-digit+ acc-rev finish-number input)])) - - (define (finish-number acc-rev input) - (define s (list->string (reverse acc-rev))) - (define n (string->number s 10)) - (cond [(not n) #f] - [(and (flonum? n) (member input '((#\f) (#\F)))) (float n)] - [(equal? input '()) n] - [else #f])) - ;;--------------------------------------------------------------------------- ;; Main entry point to parser