2012-04-24 52 views

回答

1

不是最有效的:

(define (make-bools n) 
    (if (= n 0) 
    '() 
    (append (addhead 'T (make-bools (- n 1))) 
      (addhead 'F (make-bools (- n 1)))))) 

; Yield copy of l with h added on to head of each list in l 
(define (addhead h l) 
    (if (null? l) 
     l 
     (cons (cons h (car l)) (addhead h (cdr l))))) 
+0

作品雖然有一定的誤差。如果n = 0,則需要返回'(()),否則添加頭不能在'() – randomThought 2012-04-24 01:00:00

+0

好點上工作,甚至對於(make-bools 0)也是合理的值。 – 2012-04-24 01:32:24

3

此作品在球拍:

#lang racket 

(define (generate-binary-combinations n) 
    (if (zero? n) 
     '(()) 
     (for*/list ((y (in-list (generate-binary-combinations (sub1 n)))) 
        (x (in-list '(T F)))) 
     (cons x y)))) 

(generate-binary-combinations 3) 
> '((T T T) (F T T) (T F T) (F F T) (T T F) (F T F) (T F F) (F F F)) 

(generate-binary-combinations 0) 
> '(())