Exercise2-58 <---> Exercise2-60

Exercise 2.59

Implement the union-set operation for the unordered-list representation of sets.


Ru: Реализуйте операцию union-set для представления множеств в виде неупорядоченных списков.


Scheme solution:

(define (union-set set1 set2)
  (cond ((null? set1) set2)
        ((element-of-set? (car set1) set2)
         (union-set (cdr set1) set2))
        (else (cons (car set1) (union-set (cdr set1) set2)))))

Haskell solution:

Note that Haskell's Data.List module already has a "union" function.

union_set :: (Eq a) => [a] -> [a] -> [a]
union_set set1 set2 = set1 ++ filter (`notElem` set1) set2

OCaml solution:

let union_set set1 set2 = set1 @ List.filter (fun x -> not (List.mem x set1)) set2

Exercise2-58 <---> Exercise2-60


Comments

Can also do this using the 'filter' procedure from section 2.2.3 thusly:

(define (union-set set1 set2)

  • (append set1
    • (filter (lambda (x)
      • (not (element-of-set? x set1)))
      • set2)))
Posted by wasp at 2008-03-12 17:32:23

great solution,wasp !

Posted by lenatis :) at 2008-08-27 12:22:45 X
wasp is using A u B = A + (B - A n B) for the intersection set, we can write (define (intersection-set a b)

    * (filter (lambda (x) (element-of-set? x a) b))
Posted by host172 at 2009-01-27 05:06:20 X
wasp is using A u B = A + (B - A n B)


for the intersection set, we can write

(define (intersection-set a b)
  (filter (lambda (x) (element-of-set? x a) b))
Posted by host172 at 2009-01-27 05:07:17 X

:) :)) :( ;) :\ |) X-( B) Markup

Exercise2-59 (last edited 2009-01-04 06:26:09 by FirstnameLastname)