简体   繁体   中英

How do i convert a list of strings into a list of lists in Racket

I have a problem with converting a list of strings into a list of lists, as well as conversion of the items within each of the lists. Let's say I have the list:

("ZZ 9 8" "T 188 8" "L 5 10") how could i convert this to become;

(("ZZ" 9 8) ("T" 188 8) ("L" 5 10)) so that the numbers are numbers and the strings are strings?

You can map over each string, splitting it, leaving the first element as a string and converting the other elements to numbers. Something like this:

(define (convert strs)
  (map (lambda (str)
         (let ((strlist (string-split str)))
           (cons (first strlist)
                 (map string->number (rest strlist)))))
       strs))

For example:

(convert '("ZZ 9 8" "T 188 8" "L 5 10"))
=> '(("ZZ" 9 8) ("T" 188 8) ("L" 5 10))

It is fragile to assume that only the first token in an input string should be left as a string and that all other strings should be converted to numbers. You can solve the problem easily by defining two procedures.

The parse-nstring procedure takes a string which may contain number tokens and returns a list of strings and numbers. The string->number procedure returns #f when it is unable to convert a string to a number. parse-nstring only uses the result of string->number when the conversion was successful; otherwise the original token is kept. This is accomplished by splitting the original space-delimited string into substrings, and mapping over that list with an anonymous procedure that takes a substring and returns a number if it can be converted to a number, or the original substring otherwise.

The parse-nstrings procedure takes a list of strings and returns a list containing the results of parsing each string. This procedure simply maps the parse-nstring procedure over the input list.

(define (parse-nstring str)
  (let ((substs (string-split str)))
    (map (lambda (subst) (let ((token (string->number subst)))
                           (or token subst)))
         substs)))

(define (parse-nstrings strs)
  (map parse-nstring strs))
strings-to-lists.rkt> (parse-nstrings '("ZZ 9 8" "T 188 8" "L 5 10"))
'(("ZZ" 9 8) ("T" 188 8) ("L" 5 10))

strings-to-lists.rkt> (parse-nstrings '("THX 11 38" "99 Red Ballons" "1 O'Clock 2 O'Clock 3 O'Clock Rock"))
'(("THX" 11 38) (99 "Red" "Ballons") (1 "O'Clock" 2 "O'Clock" 3 "O'Clock" "Rock"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM