2014-02-19 66 views
1

我是Scheme的新手,我正在尝试编写一个程序,在每个步骤中都将一个符号添加到字符串中,并在最后返回字符串。 例如,使像一个字符串“TFTFT ......”在程序中向字符串变量添加符号

(define str "") 
(define foo 
     (lambda (x) 
      (
       (if(eqv? (car x) 3) (string-append str "T") (string-append str "F")) 
       (if(eqv? (car (cdr x)) 4) (string-append str "T") (string-append str "F")) 
       (if(eqv? (cdr (cdr x)) 5) (string-append str "T") (string-append str "F")) 
      ))) 

我想要的结果如下:

> (foo '(3 4 5)) 
"TTT" 
> (foo '(3 6 5)) 
"TFT" 

我知道,串追加一部分是不正确的。你能帮我一下吗?

此外,当我尝试运行该程序时出现错误: 应用程序:不是一个过程; 预期考虑到可以应用到参数的过程 : 参数...... “T”: “F” “F”

+0

嗯,一件事'(cdr(cdr x))''会返回一个列表。你想''(car(cdr(cdr x)))'元素'5'。 – kbshimmyo

+0

是的,你是对的。我没有仔细写。我只是设计它来指出我的问题,即在递归过程中如何“将一些符号附加到一个字符串”。例如: : initila value:str =“”; next recurion:str =“0”; next recurion:str =“01”; next recurion:str =“011”; next recurion:str =“0110”; ...然后将此字符串作为输出。 –

回答

0

你说

制作像“TFTFT字符串.. 。“

这听起来像你正在尝试对任何长度的输入序列执行此操作,而不仅仅是3个数字的列表。选择T与F来追加到字符串的规则似乎是是列表元素是否比前面的列表元素大1。这一切是正确的吗?

如果这就是你想要做的,你需要递归地做这件事,而不是试图通过写更多的if-clause来测试同一行中的所有元素。尝试是这样的:

;; foo-rec: list-of-ints string int -> string 
;; Returns a sequence of TFT... values indicating whether the corresponding nth position in 
;; the input list myseq contains the value (expected_val + n - 1). 
(define (foo-rec myseq mystr expected_val) 
    (cond 
    [(empty? myseq) mystr] 
    [(= (car myseq) expected_val) (foo-rec (cdr myseq) (string-append mystr "T") (add1 expected_val))] 
    [else (foo-rec (cdr myseq) (string-append mystr "F") (add1 expected_val))])) 

这给

> (foo-rec '(3 4 5) "" 3) 
"TTT" 
> (foo-rec '(3 6 5) "" 3) 
"TFT" 
> (foo-rec '(3) "" 3) 
"T" 
> (foo-rec empty "" 3) 
"" 
> (foo-rec '(3 4 5 7 7 8) "" 3) 
"TTTFTT" 

更多关于递归,看看在"How to Design Programs" (HTDP)(或its headier brother, SICP)。前者使得阅读非常轻松。

+0

谢谢你的回答。 我想我不能将任何其他输入作为字符串传递给函数foo。 我可以用另一种方式做到吗? –