Domanda

I'm trying to learn how to use match in scheme. I sort of understand how it works with really short problems (ie: defining length is just two lines) but not with problems where there's more than one input, and helper programs. For example, here's a popular way of defining union:

(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))])))

How do you do this using match in both programs? (or would you even need two programs?)

È stato utile?

Soluzione

the first one could be implemented like that:

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

then the second is easy

(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))]))))

maybe there is a smarter way to avoid these one argument let lambdas but i'm still learning ;)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top