1

基本上,给定 n,例如 3,我如何创建 T 和 F 的所有组合的值列表

例如。对于 n = 3,(make-bools 3) 应该返回 ((TTT), (TTF), ... (FFF))

这类似于问题Function to return all combination of n booleans? 但要在计划中实施

4

2 回答 2

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)
> '(())
于 2012-04-24T02:53:15.023 回答
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)))))
于 2012-04-24T00:49:44.010 回答