此函数应返回L的传递闭包。例如:
(Transitive-Closure'((a b) (b c) (a c))) ---> '((a b) (b c) (a c))
(Transitive-Closure'((a a) (b b) (c c))) ---> '((a a) (b b) (c c))
(Transitive-Closure'((a b) (b a))) ---> '((a b) (b a) (a a) (b b)))
(Transitive-Closure'((a b) (b a) (a a)))---> '((a b) (b a) (a a) (b b))
(Transitive-Closure'((a b) (b a) (a a) (b b)))---> '((a b) (b a) (a a) (b b))
(Transitive-Closure'())---> '()这是我在球拍中拥有的:
(define (Transitive-Closure L)
(apply append
; Iterate over each pair (a b) in L,
(map (lambda (x)
;Iterate over each pair (c d) in L,
(map (lambda (y)
(let ([a (car x)]
[b (cadr x)]
[c (car y)]
[d (cadr y)])
;if b equal to c, and (a d) does not exist in L, it will add (a d) to L . Otherwise, return L.
(if (and (eq? b c) (not (member (list a d) L)))
(list a d)
(append x))))L)) L)))我的代码只有在不可传递的情况下才能工作。如何修改代码以避免在传递时返回重复的对?
例如,我的输出:
;This is wrong. It should return '((a b)(b c)(a c))
(Transitive-Closure '((a b)(b c)(a c))) ---> '((a b) (a b) (a b) (b c) (b c) (b c) (a c) (a c) (a c))
; This is right.
(Transitive-Closure '((a b)(b a)))---> '((a b) (a a) (b b) (b a))发布于 2020-11-14 01:31:35
这不是一个map问题,这是一个foldr问题,因为您没有在适当的位置修改列表,而是将列表压缩为一项。该项目恰好是一个list,但重要的是,该列表可以小于map可以返回的内容。此外,您还可以根据累加器中是否已经存在该对来检查是否应该在另一条if语句中添加。
如果顺序无关紧要(我假设,你只是想要集合,如果不是这样,请让我知道)
(define (Transitive-Closure L)
; Iterate over each pair (a b) in L,
(foldr (lambda (x transitive-pairs)
;Iterate over each pair (c d) in L,
(foldr (lambda (y sofar)
(let ([a (car x)]
[b (cadr x)]
[c (car y)]
[d (cadr y)])
;if b equal to c, and (a d) does not exist in L, it will add (a d) to L . Otherwise, return L.
(cond [(and (eq? b c) (not (member (list a d) L))) (cons (list a d) sofar)]
[(not (member x sofar)) (cons x sofar)]
[else sofar])))
transitive-pairs L)) '() L))
(check-expect (Transitive-Closure '((a b) (b c) (a c))) '((a b) (b c) (a c)))
(check-expect (Transitive-Closure '((a a) (b b) (c c))) '((a a) (b b) (c c)))
(check-expect (Transitive-Closure '((a b) (b a))) '((a b) (a a) (b b) (b a)))
(check-expect (Transitive-Closure '((a b) (b a) (a a))) '((a b) (b b) (b a) (a a)))
(check-expect (Transitive-Closure '((a b) (b a) (a a) (b b))) '((a b) (b a) (a a) (b b)))https://stackoverflow.com/questions/64816634
复制相似问题