方案中所有大小的n个子列表

时间:2019-03-16 00:07:05

标签: functional-programming scheme computer-science

我是计划语言的新手,我正在尝试构建一个方法,该方法获取一个列表和一个数字“ n”作为参数,并返回大小为n的所有子列表。 例如,如果该方法收到'(a b c d)和2,它将返回 '('(a b)'(b c)'(c d)) 该方法必须是递归的。 我设法得到了第一个大小为n的列表,但是从那里一直卡住了。 预先感谢。

(define sub-lists
  (lambda (lst n)
    (if (zero?  n)
        '()
        (cons (car los) (sub-lists (cdr lst) (- n 1))))))

1 个答案:

答案 0 :(得分:0)

您可以使用appendmap-

(define (choose n l)
  (cond ((zero? n)
         (list null))
        ((null? l)
         null)
        (else
         (append (map (lambda (comb)
                        (cons (car l) comb))
                      (choose (- n 1)
                              (cdr l)))
                 (choose n
                         (cdr l))))))

它为任何自然n(包括零)提供有效结果-

(choose 3 '(a b c))
;; '((a b c))

(choose 2 '(a b c))
;; '((a b) (a c) (b c))

(choose 1 '(a b c))
;; '((a) (b) (c))

(choose 0 '(a b c))
;; '(())

n的大小也超过l时,它会提供有效的结果-

(choose 4 '(a b c))
;; '()

appendmap的可能实现-

(define (append a b)
  (if (null? a)
      b
      (cons (car a)
            (append (cdr a)
                    b))))

(define (map f l)
  (if (null? l)
      null
      (cons (f (car l))
            (map f
                 (cdr l)))))

如果希望重复元素,则只需更改一个表达式-

(define (choose n l)
  (cond ((zero? n)
         (list null))
        ((null? l)
         null)
        (else
         (append (map (lambda (comb)
                        (cons (car l) comb))
                      (choose (- n 1)
                              l)) ;; change (cdr l) to l
                 (choose n
                         (cdr l))))))

组合现在包含重复的元素-

(choose 3 '(a b c))
;; '((a a a) (a a b) (a a c) (a b b) (a b c) (a c c) (b b b) (b b c) (b c c) (c c c))

(choose 2 '(a b c))
;; '((a a) (a b) (a c) (b b) (b c) (c c))

(choose 1 '(a b c))
;; '((a) (b) (c))

(choose 0 '(a b c))
;; '(())

请注意,在n超过l-的情况下存在显着差异-

(choose 4 '(a b c))
;; '((a a a a)
;;   (a a a b)
;;   (a a a c)
;;   (a a b b)
;;   (a a b c)
;;   (a a c c)
;;   (a b b b)
;;   (a b b c)
;;   (a b c c)
;;   (a c c c)
;;   (b b b b)
;;   (b b b c)
;;   (b b c c)
;;   (b c c c)
;;   (c c c c))