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)
| ||||
| Posted by wasp at 2008-03-12 17:32:23 | ||||
great solution,wasp ! | ||||
| Posted by lenatis | ||||
| 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 | ||||