Scheme 将单词列表组合成拍子中的段落

Scheme 将单词列表组合成拍子中的段落,scheme,racket,Scheme,Racket,我必须把一系列单词组合在一起才能写出段落。我做到了以下几点: (define (wordlist2para wl) (define str " ") (for ((w wl)) (set! str (string-append str w " "))) (string-trim str)) (wordlist2para '("this" "is" "a" "test")) 输出: "this is a test" "this is a test" 它可以工作,但不起作

我必须把一系列单词组合在一起才能写出段落。我做到了以下几点:

(define (wordlist2para wl)
  (define str " ")
  (for ((w wl))
    (set! str (string-append str w " ")))
  (string-trim str))

(wordlist2para '("this" "is" "a" "test"))
输出:

"this is a test"
"this is a test"

它可以工作,但不起作用。如何为此编写函数代码?

无需递归或循环,有基本函数字符串连接,请参见:


不需要递归或循环,有基本函数字符串连接,请参见:


如果我想显式地执行此操作而不使用字符串连接,我将递归并使用三种情况:

空列表生成空字符串 一个元素列表生成其唯一的元素,这避免了使用尾随分隔符 否则,将car和一个空格附加到cdr上的递归中。 像这样:

(define (wordlist2para ws)
  (cond ((null? ws) "")
        ((null? (cdr ws)) (car ws))
        (else (string-append (car ws) " " (wordlist2para (cdr ws))))))

如果我想显式地执行此操作而不使用字符串连接,我将递归并使用三种情况:

空列表生成空字符串 一个元素列表生成其唯一的元素,这避免了使用尾随分隔符 否则,将car和一个空格附加到cdr上的递归中。 像这样:

(define (wordlist2para ws)
  (cond ((null? ws) "")
        ((null? (cdr ws)) (car ws))
        (else (string-append (car ws) " " (wordlist2para (cdr ws))))))

我们有这样做的标准程序:

;; racket library or srfi/13
(string-join '("this" "is" "it"))   ; ==> "this is it"
有一种方法总是重写这些非常简单的代码。我想从rackets伟大的特性集开始,只关注带有递归过程的简单方案。请注意,在您的循环中,您正在更改两件事:wl变小,str变长,所以让我们进行以下更改:

; all things that change as arguments
(define (wordlist2para-loop wl str) 
  (if (null? wl)
      str
      (wordlist2para-loop (cdr wl)
                          (string-append str (car wl) " "))))
现在,我们只需替换循环:

(define (wordlist2para wl)
  (wordlist2para-loop wl ""))
从这里开始,您可以将helper移动到本地,或者使其成为命名let或任何其他重构,但它实际上并不会在实现中改变最终的编译结果,只是改变它的外观


注意,我还没有修复只有一个单词的bug。wordlist2para'这个;==>这实际上与中的结果完全相同,只是它是尾部递归的和功能性的。

我们有标准的过程来实现这一点:

;; racket library or srfi/13
(string-join '("this" "is" "it"))   ; ==> "this is it"
有一种方法总是重写这些非常简单的代码。我想从rackets伟大的特性集开始,只关注带有递归过程的简单方案。请注意,在您的循环中,您正在更改两件事:wl变小,str变长,所以让我们进行以下更改:

; all things that change as arguments
(define (wordlist2para-loop wl str) 
  (if (null? wl)
      str
      (wordlist2para-loop (cdr wl)
                          (string-append str (car wl) " "))))
现在,我们只需替换循环:

(define (wordlist2para wl)
  (wordlist2para-loop wl ""))
从这里开始,您可以将helper移动到本地,或者使其成为命名let或任何其他重构,但它实际上并不会在实现中改变最终的编译结果,只是改变它的外观


注意,我还没有修复只有一个单词的bug。wordlist2para'这个;==>这实际上与中的结果完全相同,只是它是尾部递归的和函数式的。

我不确定以下是否可以称为函数式的,但它确实使用了一些高阶函数:

(define (wordlist2para wl)
  (string-trim 
    (apply string-append 
        (map (lambda(x) (string-append x " ")) wl))))

(wordlist2para '("this" "is" "a" "test"))
输出:

"this is a test"
"this is a test"

我不确定下面的函数是否可以调用,但它确实使用了一些高阶函数:

(define (wordlist2para wl)
  (string-trim 
    (apply string-append 
        (map (lambda(x) (string-append x " ")) wl))))

(wordlist2para '("this" "is" "a" "test"))
输出:

"this is a test"
"this is a test"

多容易啊!谢谢,多简单啊!谢谢。很好的功能编码。很好的功能编码。很好的解释。很好的解释。