"a,b,c" 我很想编写Sche-6ren">
gpt4 book ai didi

scheme - 将字符串列表合并为逗号分隔的字符串

转载 作者:行者123 更新时间:2023-12-01 19:05:54 25 4
gpt4 key购买 nike

我需要编写一个软件,给定一个字符串列表,返回一个由输入列表元素的逗号分隔串联组成的新字符串。

(comma-con (list "a" "b" "c"))  ;=> "a,b,c"

我很想编写Scheme惯用代码。

到目前为止,我写的是:

(define (comma-con l)
(foldr
(λ (x y) (if (string? y) (string-append x "," y) x))
'()
l))

这可行,但看起来有点脏。有没有办法以更好的方式编写它,例如避免“如果”?

最佳答案

尝试使用string-join ,它完全满足您的需要,并且尽可能地惯用:

(string-join '("a" "b" "c") ",")
=> "a,b,c"

无论如何,如果您想使用折叠来解决问题,这是一个更干净的解决方案(假设输入列表非空):

(define (comma-con lst)
(foldl (λ (e acc) (string-append acc "," e))
(first lst)
(rest lst)))

关于scheme - 将字符串列表合并为逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24063199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com