在 Racket 中创建联合函数

问题描述 投票:0回答:1

我正在尝试在 Racket 中创建一个函数,该函数将读取两个列表并创建两个集合中元素的并集。这是我为尝试模拟此功能而创建的代码:

(define (union set1 set2)
  (define unilst '())
  (letrec ([build (lambda (build1 build2 lst)
      (define a '())
      (define b '())
      (cond[(equal? build1 '()) 0]
           [(equal? build2 '()) 0]
           [else (set! a (first build1)) (set! b (first build2))
                 (cond
                      [(= a b) (set! lst (cons lst a))]
                      [else (set! lst (cons b lst))
                            (set! lst (cons a lst))])
                            (set! lst (cons (build (rest build1) (rest build2) lst) lst))])
                             lst)])+
    (set! unilst (build set1 set2 '()))
    unilst))

但我收到的输出是:

((((3 4 2 3 1 2) 3 4 2 3 1 2) 2 3 1 2) 1 2)

我应该以不同的方式处理我的递归吗?还是我遗漏了什么?

任何帮助将不胜感激。

recursion racket unions
1个回答
0
投票

这看起来像是您尝试用不同的语言编写代码,但使用 Scheme 语法。
使用

set!
几乎没有任何意义。

集合

s1
s2
的并集是

  • 如果
    s1
    为空,则
    s2
  • 如果
    s2
    为空,则
    s1
  • 如果
    (first s1)
    s2
    的成员,那么
    (rest s1)
    s2
  • 的并集
  • 否则,将
    (first s1)
    添加到
    (rest s1)
    s2
  • 的并集
(define (union s1 s2)
  (cond [(empty? s1) s2]
        [(empty? s2) s1]
        [(member (first s1) s2) (union (rest s1) s2)]
        [else (cons (first s1) (union (rest s1) s2))]))

测试:

> (union '() '())
'()
> (union '() '(1 2 3))
'(1 2 3)
> (union '(1 2 3) '())
'(1 2 3)
> (union '(1 2 3) '(1 2 3))
'(1 2 3)
> (union '(1 2 3) '(4 5 3))
'(1 2 4 5 3)
> (union '(3 2 1) '(4 5 3))
'(2 1 4 5 3)

当然,如果输出应该是一个集合,输入也必须是集合(即没有重复值)。

© www.soinside.com 2019 - 2024. All rights reserved.