提取以前未遇到的数据对的数据。

huangapple go评论53阅读模式
英文:

Extracting data of pairs without the data that encountered before

问题

I don't want to translate the code part. However, I can provide a translation of the non-code portion of your text:

我有一些数据,其中包含一些配对数据。但是有些配对在之前已经遇到过。我不想再次提取相同的数据。例如,我有像这样的数据。

所以,如您所见,p3的第一个元素与p1相同。但是p0的第一个元素之前已经出现过。

首先,我首先像这样定义了所有的配对:

然后,我使用递归提取了所有的配对:

但是,我不想再次提取(2 3 1),因为我之前已经遇到过它。我该如何检测这一点?

英文:

I have a data which inside of some pairs. But some pairs go a pair that encountered before. I don't want to extract same data again. For example I have a data like this.

So, as you see p3's first item goes p1. However p0's first item has gone that element before.

First, I have defined all pairs first like this

(define p2 (cons 2 3))
(define p4 (cons 4 5))
(define p1 (cons p2 1))
(define p3 (cons p1 p4))
(define p0 (cons p1 p3)) 

then I extracted all pairs by using recursion

(define (extract pair)
  (if (pair? pair) (append (extract (car pair)) (extract (cdr pair))) (list pair)))

And I get the result of

(2 3 1 2 3 1 4 5)

However, I don't want to extract (2 3 1) again because I have encountered before. How can I detect that?

答案1

得分: 0

请尝试使用(union x y)代替(append x y)

(define (extract pair)
   (if (pair? pair)
       (union (extract (car pair)) (extract (cdr pair)))
       (list pair)))
       
(define (union A B)
   (cond [(empty? A) B]
         [else 
            (let ([C (union (rest A) B)])
                 (cond [(member (first A) C) C]
                       [else (cons (first A) C)]))]))
                       
(define p2 (cons 2 3))
(define p4 (cons 4 5))
(define p1 (cons p2 1))
(define p3 (cons p1 p4))
(define p0 (cons p1 p3)) 

(extract p0)
英文:

Try to use (union x y) instead of (append x y):

(define (extract pair)
   (if (pair? pair)
       (union (extract (car pair)) (extract (cdr pair)))
       (list pair)))
       
(define (union A B)
   (cond [(empty? A) B]
         [else 
            (let ([C (union (rest A) B)])
                 (cond [(member (first A) C) C]
                       [else (cons (first A) C)]))]))
                       
(define p2 (cons 2 3))
(define p4 (cons 4 5))
(define p1 (cons p2 1))
(define p3 (cons p1 p4))
(define p0 (cons p1 p3)) 

(extract p0)

huangapple
  • 本文由 发表于 2023年5月17日 19:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定