在球拍中列表到字符串的转换 [英] List to string conversion in Racket

查看:66
本文介绍了在球拍中列表到字符串的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在DrRacket中将列表转换为字符串?例如,如何将'((红色黄色蓝色绿色)转换为红色黄色蓝色绿色"?我尝试使用list-> string,但这似乎仅适用于字符.

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.

推荐答案

这里的窍门是映射到作为输入接收的符号的列表上,依次将每个符号转换为字符串,并注意除了最后一个,在每个之间添加一个空格.像这样:

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"

这篇关于在球拍中列表到字符串的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆