【发布时间】:2020-01-15 13:08:14
【问题描述】:
使用前面构造的函数contains,编写一个函数intersection,它接受两个列表(建模集)并返回一个列表,该列表是两个集合的交集。所以
intersection([1, 2, 3], [1, 3])
将返回[1, 3]。
使用前面构造的函数contains,编写一个函数difference,它接受两个列表并返回一个列表,该列表对第一个集合与第二个集合(集合A - 集合B)的差异进行建模。
我已经创建了下面的代码contains,现在我的目标是创建intersection 和difference 函数。
fun contains(x, []) = false
| contains(x, y::rest) =
if x = y
then true
else contains(x, rest);
fun intersection([], y) = []
| intersection(x, y) = if x = y
then [x,y]
else [];;
尝试一下:
- intersection([1, 2], [2, 3]);
val it = [] : int list list
【问题讨论】:
-
需要递归,需要研究集合交集的定义。