" deleteAll"方法只删除一个事件

时间:2014-11-29 19:56:58

标签: list sml smlnj

我被要求编写标准ML程序,该程序会删除另一个列表中每个列表的出现。对于我的生活,我无法理解我的代码有什么问题。任何帮助,将不胜感激! 我对此计划的意见如下:

deleteAll [1,2,3] [3,2,1,2,3,2,1,2,3];

但是我的输出是这样的:

val it = [3,2,2,1,2,3]:int list

应该是:[3,2,2];

fun length(x) = if x = [] then 0 else 1+length(tl(x));

val length = fn : ''a list -> int

fun drop 0 L = L
|   drop n [] = raise c4
|   drop n (h::t) = drop (n-1) t;

val drop = fn : int -> 'a list -> 'a list

fun starts [] _ = true
|   starts _ [] = false
|   starts (h::t) (x::xs) = if(h=x) then starts t xs else false;

val starts = fn : ''a list -> ''a list -> bool


fun deleteAll [] _ = []
|   deleteAll xs [] = xs
|   deleteAll (x::xs) (y::ys) = if(starts (x::xs) (y::ys))
    then deleteAll (x::xs) (drop (length(x::xs)) (y::ys))
    else y::(deleteAll (x::xs) ys);
val deleteAll = fn : ''a list -> ''a list -> ''a list

1 个答案:

答案 0 :(得分:0)

首先,您不需要创建长度函数,因为length是一个内置函数,它返回一个表示'a list'元素的int。

还有一件事,你在函数drop中引发异常c4。然后你还应该在程序的开头加入它。

您的代码不起作用的主要原因是您的deleteAll函数基本情况。更正后的版本应为:

fun deleteAll [] xs = xs (* when the first list is empty, it should return the original list *)
|   deleteAll xs [] = [] (* when the second list is empty, it should return an empty list *)
|   deleteAll (x::xs) (y::ys) = if(starts (x::xs) (y::ys))
                                then deleteAll (x::xs) (drop (length(x::xs)) (y::ys))
                                else y::(deleteAll (x::xs) ys);

其余的都很好!更改后,答案应该是正确的:)

- deleteAll [1,2,3] [3,2,1,2,3,2,1,2,3];
val it = [3,2,2] : int list