使用循环返回列表

时间:2017-11-27 21:35:53

标签: loops for-loop scheme lisp racket

我是Racket的新手。我试图使用循环返回列表列表。该代码有效,但它只打印其中一个元素3次而不评估其他条件,导致重复。如何遍历每个条件并为每个条件打印一个元素而不重复?

(define position_                                                                                                                             
  (lambda
      (list_) 
    (let ([size 3]) ;
      (for/list ([binary (in-range 0 size)])
        (cond [(not (empty? list_))
               (cond((list-ref list_ 0) (cond ((equal? (list-ref list_ 0) 1) (list (vector-ref Table 0) HIGH)) ((equal? (list-ref list_ 0) 0) (list (vector-ref Table 0) LOW))))                 
                    ((list-ref list_ 1) (cond ((equal? (list-ref list_ 1) 1) (list (vector-ref Table 1) HIGH)) ((equal? (list-ref list_ 1) 0) (list (vector-ref Table 1) LOW)))) 
                    ((list-ref list_ 2) (cond ((equal? (list-ref list_ 2) 1) (list (vector-ref Table 2) HIGH)) ((equal? (list-ref list_ 2) 0) (list (vector-ref Table 2) LOW))))  
               )])
        ))))

2 个答案:

答案 0 :(得分:4)

cond只有一个字词。这意味着你做了这样的事情:

(cond [(not (empty? list_)) ...]
      [else 'pigs-are-flying]) ; what happens when the list is not empty

现在结果pigs-are-flying只是我的建议。事实上,报告明确指出了它,这意味着一切顺利。

还要知道cond是Scheme的if-elseif-else,因此很少需要嵌套cond。例如。像这样的代码:

(cond [p1 c1]
      [else (cond [p2 c2]
                  [else a2])])

写作难度很大:

(cond [p1 c1]
      [p2 c2]
      [else a2])

如果你想这样做:

(cond [p1   
       (cond [p2 c2] 
             [else a2])]
      [else a1])

您可以否定谓词以获得相同的扁平行为:

(cond [(not p1) a1]
      [p2 c2]
      [else a2])

作为一种风格评论。结束括号不应该在它自己的行上。它应该是前一行的朋友。它是人类阅读的标识,而不是括号。 DrRacket为你做到了这一点,所以不需要养成坏习惯。

答案 1 :(得分:0)

我不得不改变代码的逻辑和语法,但它现在完美地工作

(define position_                                                                                                                             
  (lambda
      (list_) 
    (let ([size  (length list_) ]) ;
      (for/list ([binary (in-range 0 size)])
        (cond [(not (empty? list_))
               (cond[ (equal? binary 0) (if (equal? (list-ref list_ binary) 1) (list (vector-ref Table 0) HIGH) (list (vector-ref Table 0) LOW) )]
                     [ (equal? binary 1) (if (equal? (list-ref list_ binary) 1) (list (vector-ref Table 1) HIGH) (list (vector-ref Table 1) LOW))]
                     [ (equal? binary 2) (if (equal? (list-ref list_ binary) 1) (list (vector-ref Table 2) HIGH) (list (vector-ref Table 2) LOW))]

                    )
               ]
               ))
        )))