从另一个

时间:2015-10-28 19:12:47

标签: list sml

我试图编写一个删除list1的程序,如果它在list2中。

E.g

delete [1,2] [1,2,3,4]
  => [3,4]

我非常接近解决它,但我的代码只删除了第二个列表中第一个列表的头部,所以......

delete [1,2] [1,2,3,4]
  => [2,3,4]

如果有人可以提供帮助,那就太好了:)

fun delete (hd1::tl1) [] = []
  | delete (hd1::tl1) (hd2::tl2) = 
      if hd1 = hd2 then delete (hd1::tl1) tl2 else hd2::delete(hd1::tl1) tl2;

2 个答案:

答案 0 :(得分:1)

您需要确定整个第一个列表是否是第二个列表的开头。

你想要建立在你之前所做的事情上 - 当你正在学习的时候,你最近经常做一些有用的事情。

如果函数start确定一个列表是否是另一个列表的开头,则可以编写

fun delete xs ys = if start xs ys
                   then <...>
                   else (hd ys) :: (delete xs (tl ys))

有趣的部分留作练习(几乎可以肯定看到可以使用的库函数)。

答案 1 :(得分:0)

取名单之间的分离;

A-[1,2]B-[1,2,3,4] list(set(A) - set(B)) which returns [3,4]

然后listcomprehension;

diff = [3,4] [x for x in B if x not in diff]
相关问题