List to string conversion in Racket

浪尽此生 提交于 2019-12-06 03:31:02

问题


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) " ")


来源:https://stackoverflow.com/questions/15543935/list-to-string-conversion-in-racket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!