如果第一个列表存在于第二个列表中,我如何创建一个将两个列表作为 args 和 returns true 的函数?

How can I make a function that takes two lists as args and returns true if the first list exists in the second?

我必须在 sml/nj 中写这个 我试了一下,这就是我所做的:

当我 运行 函数时,我希望 all 函数为 return 一个正数,但是例如当我给它 [1,2,3] [1,1,2,3,1,2,3,1] 时 returns 非穷举匹配失败。 该功能有什么问题,我该怎么做才能看到元素 第一个列表的存在于第二个列表中?

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