我需要编写一个软件,给定一个字符串列表,该软件返回一个由输入列表元素的逗号分隔串联而成的新颖字符串。
(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))
可以,但是似乎有点脏。有没有一种更好的方法来编写它,例如避免使用“ if”?
尝试使用string-join
,它完全可以满足您的需求,并且非常惯用:
(string-join '("a" "b" "c") ",") => "a,b,c"
无论如何,如果您想使用fold解决问题,这是一种更简洁的解决方案(假设输入列表为非空):
(define (comma-con lst) (foldl (? (e acc) (string-append acc "," e)) (first lst) (rest lst)))