基本上,给定n,例如3,如何创建T和F的所有组合的值列表
例如。对于n = 3,(make-bools 3)应返回((T T T),(T T F),...(F F F))
这类似于问题Function to return all combinations of n booleans?,但要在方案
中实施答案 0 :(得分:3)
这适用于Racket:
#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)
> '(())
答案 1 :(得分: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)))))