2012-11-18 22 views
1

我想根据序列binary-e列出#t /#f语句的列表。如果binary-e中的值为0,则放入lst中的值应为#t,或者如果为1,则应该为#f。 n参数是lst应该有多长。但它总是返回一个空列表。这是我的代码:将值列入清单

(define (mysequence n)     
     (define binary-e (list 0 0 1 1 0 0 1 0 0 0 1 0 1 1 1 0 0 0 1 1 0 1 1 1 0 0 1 1 0 0 0 1 0 0 1 1 1 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 1 0 0 1 1 1 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1 1 0 0 0 0 0 1 1 0 1 0 0 0 0 1 1)) 

     (define (makelist lst k) 
      (cond((= k (- n 1)) lst)   
       ((= 0 (list-ref binary-e k)) (begin (cons #t lst) (makelist lst (+ k 1))))   
       ((= 1 (list-ref binary-e k)) (begin (cons #f lst) (makelist lst (+ k 1)))) 

      ) 
     ) 


     (makelist '() 0)  
)  

感谢您的任何帮助。

回答

3

您可以轻松地解决这个问题一个用map

(map (lambda (e) 
     (if (= e 0) #t #f)) 
    binary-e) 

或者更短:

(map zero? binary-e) 

但是如果你需要从头开始写一个解决方案,恐怕代码在这个问题上远不是一个正确的答案。我会给你一些指示,并告诉你解决方案的正确结构,所以你可以自己找到答案(因为这看起来很像作业),但你必须完全重新考虑你的答案。对于初学者来说,你不需要沿着列表的大小通:

(define (mysequence lst) 
    (cond ((<???> lst)     ; if the list is empty 
     <???>)      ; then return the empty list 
     ((= <???> <???>)    ; if the first element in the list is 0 
     (cons <???>     ; then `cons` #t 
       (mysequence <???>))) ; and process the rest of the list 
     ((= <???> <???>)    ; if the first element in the list is 1 
     (cons <???>     ; then `cons` #f 
       (mysequence <???>))))) ; and process the rest of the list 

或者更短:

(define (mysequence lst) 
    (if (<???> lst)   ; if the list is empty 
     <???>     ; then return the empty list 
     (cons     ; else `cons` 
     <???>     ; if the first element in list is zero #t else #f 
     (mysequence <???>)))) ; process the rest of the list 

无论哪种方式,这样称呼它:

(define binary-e <???>) ; define the list outside the procedure 
(mysequence binary-e) ; and pass it along as a parameter 

当前在您的问题中的代码看起来像是为程序语言写的 - 特别是使用list-ref来解决这类问题并不完全正确。你必须停止思考C/C++/C#/ Java或任何你平常的编程语言,并开始思考在Scheme方式 - 这有利于更实用的编程风格。