List to string conversion in Racket

2019-04-08 20:30发布

问题:

How do I convert a list into a string in DrRacket? For example, how do I convert '(red yellow blue green) into "red yellow blue green"? I tried using list->string but that seems to work only for characters.

回答1:

The trick here is mapping over the list of symbols received as input, converting each one in turn to a string, taking care of adding a white space in-between each one except the last. Something like this:

(define (slist->string slst)
  (cond ((empty? slst) "")
        ((empty? (rest slst)) (symbol->string (first slst)))
        (else (string-append (symbol->string (first slst))
                             " "
                             (slist->string (rest slst))))))

Or even simpler, using higher-order procedures:

(define (slist->string slst)
  (string-join (map symbol->string slst) " "))

Either way, it works as expected:

(slist->string '(red yellow blue green))
=> "red yellow blue green"

And just to be thorough, if the input list were a list of strings (not symbols as in the question), the answer would be:

(define strlist (list "red" "yellow" "blue" "green"))
(string-join strlist " ")
=> "red yellow blue green"


回答2:

Racket supports a number of utility functions that make this easy. If all you want is to see what's in the list, you might be happy with just "display". If you care about not having the parens, you can use string-join.

#lang racket

(define my-list '(a big dog))

;; the easy way (has parens):
(~a my-list)

;; slightly harder
(string-join (map ~a my-list) " ")