A "read" variant that works with format strings would be a useful
addition I think.
Matthew, your solution is clever :) (but with symbols instead of strings).
Another alternative could be to use match:
#lang racket
(define (trim-brackets str)
(string-trim str #rx"\\[|\\]|,"))
(define (pad n w)
(~r n #:pad-string "0" #:min-width w))
(parameterize ([current-input-port (open-input-file "file.txt")])
(for ([ln (in-lines)])
(match (string-split (trim-brackets ln) ", ")
[(list (app string->number x)) (displayln x)]
[(list (app string->number x) y (app string->number z))
(printf "[~a, ~a, ~a]\n" (pad x 2) y (pad z 4))])))
or if you are willing to write a macro:
#lang racket
(define (trim-brackets str)
(string-trim str #rx"\\[|\\]|,"))
(define (pad n w)
(~r n #:pad-string "0" #:min-width w))
(define-match-expander numstr
(syntax-rules () [(_ x) (app string->number x)]))
(parameterize ([current-input-port (open-input-file "file.txt")])
(for ([ln (in-lines)])
(match (string-split (trim-brackets ln) ", ")
[(list (numstr x)) (displayln x)]
[(list (numstr x) y (numstr z))
(printf "[~a, ~a, ~a]\n" (pad x 2) y (pad z 4))])))
(yes, I didnt close the port)
On Tue, Mar 22, 2016 at 6:34 PM, Matthew Butterick <[email protected]> wrote:
>> Then, for all rows, read and split the string. The best that i have found to
>> do that is using regular expressions.
>>
>> (define split-row (regexp-match #rx"\\[(.+), (.+), (.+)\\]" (read-line)))
>>
>> Then you have to manually convert the substrings into values
>>
>> (define a (string->number (second split-row)))
>> (define b (third split-row))
>> (define c (string->number (fourth split-row)))
>
> This kind of destructuring & conversion from strings to values can sometimes
> be more conveniently handled by converting your source data into something
> that looks like Racket S-expressions (in this case, by removing the commas)
> and then calling `read` to do the rest, e.g.
>
> #lang racket
> (with-input-from-file "data.txt"
> (λ _ (for/list ([ln (in-lines)])
> (read (open-input-string (string-replace ln "," ""))))))
>
> --
> You received this message because you are subscribed to the Google Groups
> "Racket Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
--
You received this message because you are subscribed to the Google Groups
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.