递归笛卡尔积函数球拍
Recursive Cartesian Product Function Racket
我正在尝试实现一个递归函数来查找两个集合的笛卡尔积。我目前的代码如下:
(define (cartesian-product set-1 set-2)
(let (b (set 2))
(cond [(empty? set-1) '()]
[(empty? set-2) (cartesian-product (rest set-1) b)]
[else (append (list (list (first set-1) (first set-2))) (cartesian product set-1 (rest set-2)))]))))
但是,我的逻辑有错误,我无法准确指出。感谢您的帮助!
用两个循环而不是一个循环怎么样?
(define (cartesian-product set-1 set-2)
(define (cartesian-product-helper element set)
(if (empty? set)
set
(cons (list element (first set))
(cartesian-product-helper element (rest set)))))
(if (or (empty? set-1)
(empty? set-2))
empty
(cons (cartesian-product-helper (first set-1) set-2)
(cartesian-product (rest set-1) set-2))))
您在您的逻辑中发现了问题并试图在 b
中保存 set-2
(您输入错误为 (set 2)
),但此值将在每次递归时被覆盖称呼。如果您改为调用辅助函数,它循环遍历一组的所有元素以及另一组的第一个元素,您的问题就会消失。
Welcome to DrRacket, version 6.1.1 [3m].
Language: racket; memory limit: 128 MB.
> (cartesian-product '(1 2 3) '(x y z))
'(((1 x) (1 y) (1 z))
((2 x) (2 y) (2 z))
((3 x) (3 y) (3 z)))
> (cartesian-product '(1 2 3) '())
'()
> (cartesian-product '() '(x y z))
'()
或者,更像球拍的东西:
(define (cartesian-product set-1 set-2)
(if (or (empty? set-1)
(empty? set-2))
empty
(for/list ([i set-1])
(for/list ([j set-2])
(list i j)))))
我正在尝试实现一个递归函数来查找两个集合的笛卡尔积。我目前的代码如下:
(define (cartesian-product set-1 set-2)
(let (b (set 2))
(cond [(empty? set-1) '()]
[(empty? set-2) (cartesian-product (rest set-1) b)]
[else (append (list (list (first set-1) (first set-2))) (cartesian product set-1 (rest set-2)))]))))
但是,我的逻辑有错误,我无法准确指出。感谢您的帮助!
用两个循环而不是一个循环怎么样?
(define (cartesian-product set-1 set-2)
(define (cartesian-product-helper element set)
(if (empty? set)
set
(cons (list element (first set))
(cartesian-product-helper element (rest set)))))
(if (or (empty? set-1)
(empty? set-2))
empty
(cons (cartesian-product-helper (first set-1) set-2)
(cartesian-product (rest set-1) set-2))))
您在您的逻辑中发现了问题并试图在 b
中保存 set-2
(您输入错误为 (set 2)
),但此值将在每次递归时被覆盖称呼。如果您改为调用辅助函数,它循环遍历一组的所有元素以及另一组的第一个元素,您的问题就会消失。
Welcome to DrRacket, version 6.1.1 [3m].
Language: racket; memory limit: 128 MB.
> (cartesian-product '(1 2 3) '(x y z))
'(((1 x) (1 y) (1 z))
((2 x) (2 y) (2 z))
((3 x) (3 y) (3 z)))
> (cartesian-product '(1 2 3) '())
'()
> (cartesian-product '() '(x y z))
'()
或者,更像球拍的东西:
(define (cartesian-product set-1 set-2)
(if (or (empty? set-1)
(empty? set-2))
empty
(for/list ([i set-1])
(for/list ([j set-2])
(list i j)))))