我必须在sml / nj中写这个我尝试了,这就是我做的:
我希望all函数在运行函数时返回正数,但是例如当我给[1,2,3] [1,1,2,3,1,2,3,1]
它返回非穷举匹配失败时。这个函数有什么问题,我该怎么做才能看出第一个列表中的元素是否存在于第二个列表中?
fun elem num [] = false
| elem num (x::xs) = if num = x then true else elem num xs
fun all [] [] =
let
fun qwe [] [] acc = acc
| qwe (x::xs) (z::zs) acc = if elem x (z::zs) then qwe xs (z::zs) (1+acc) else qwe xs (z::zs) acc
in
qwe [] [] 0
end
在你对all
的定义中,你似乎正在考虑将[]
视为通用列表而不是空列表。
实际出现在你的all
定义中的唯一模式是[] []
(两个空列表)。最重要的是非穷举匹配的情况。
由于辅助函数qwe
完成了实际工作,因此在all
本身上进行模式匹配确实没有任何意义。 all
的整体形式可能是:
fun all xs ys =
let
fun qwe = (*insert definition*)
in
qwe xs ys 0
end;
(在这里使用zs
而不是ys
看起来有点尴尬)
que
的定义应该有2-4种模式。 4模式定义(某些函数需要在两个列表上运行):
fun qwe [] [] acc = (*insert def*)
| qwe [] (y::ys) acc = (*insert def*)
| qwe (x::xs) [] acc = (*insert def*)
| qwe (x::xs) (y::ys) acc = (*insert def*)
最后给出了4个案例,第一个列表和第二个列表的每个布尔组合一个为空。有时您不需要为每个代码编写单独的代码。例如,
fun qwe [] [] acc = (*insert def*)
| qwe [] ys acc = (*insert def*)
| qwe (x::xs) ys acc = (*insert def*)
将第3和第4个案例合并为一个案例。
如果你看一下elem
的实际定义,你会发现它很好地处理了空ys
的情况,所以在qwe
的定义中,你真的可以根据xs
的作用有两种模式:
fun qwe [] ys acc = (*insert def*)
| qwe (x::xs) ys acc = (*insert def*)
由于ys
可以匹配空列表和非空列表,因此上述模板是详尽无遗的。
对于以上两个que
案例的适当定义(你基本上已经拥有),你的函数all
将起作用:
- all [1,2,3] [1,1,2,3,1,2,3,1];
val it = 3 : int