1

我正在尝试学习如何在方案中使用匹配。我有点理解它如何处理非常短的问题(即:定义长度只是两行),但不适用于有多个输入和辅助程序的问题。例如,这是定义联合的一种流行方式:

(define ele? 
  (lambda (ele ls)
   (cond
    [(null? ls) #f]
    [(eq? ele (car ls)) #t]
    [else (ele? ele (cdr ls))])))

(define union
 (lambda (ls1 ls2)
  (cond
   [(null? ls2) ls1]
   [(ele? (car ls2) ls1) (union ls1 (cdr ls2))]
   [else (union (cons (car ls2) ls1) (cdr ls2))])))

您如何在两个程序中使用 match 来做到这一点?(或者你甚至需要两个程序?)

4

1 回答 1

1

第一个可以这样实现:

(define ele?
  (lambda (a b)
    (let ((isa? (lambda (x) (eq? (car x) a))))
      (match b [(? null?) #f]
               [(? isa?) #t]
               [_ (ele? a (cdr b))]))))

然后第二个很容易

(define uni
  (lambda (ls1 ls2)
    (let ((carinls2? (lambda (x) (ele? (car x) ls1))))
      (match ls2 [(? null?) ls1]
                 [(? carinls2?) (uni ls1 (cdr ls2))]
                 [_ (uni (cons (car ls2) ls1) (cdr ls2))]))))

也许有一种更聪明的方法可以避免这些参数让 lambdas 但我仍在学习;)

于 2012-09-06T01:21:13.527 回答