【问题标题】:Extract duplicates from nested list in SML从 SML 中的嵌套列表中提取重复项
【发布时间】:2013-02-11 07:28:26
【问题描述】:

我在 SML 中有一个返回嵌套列表的函数:

[["A", "B", "C"], ["A", "B"], ["B", "C"]]]

是否可以提取出现在这些列表中的元素?即输出“B”?

我尝试了List.filter (fn y=>(fn x=> x=y)) lst 的效果,但无济于事.. 有什么提示吗?

【问题讨论】:

  • 我不太确定你想要什么。您说“提取重复项”-您是指所有子列表中的内容吗?出现不止一次的事情?无论如何,输出单个值似乎没有意义,因为所有列表中可能出现多个值。

标签: list duplicates sml duplicate-removal smlnj


【解决方案1】:

我假设您提供的示例嵌套列表具有代表性,即元素是唯一且有序的。我还将省略任何显式类型或参数化比较函数,因此这些函数将对整数而不是字符串进行操作。

首先,将问题分解为成对比较列表。定义一个辅助函数common 来查找一对有序列表的共同元素。它可能看起来像这样:

fun common(xs, []) = []
  | common([], ys) = []
  | common(x::xs, y::ys) = if x=y then x::common(xs, ys) 
                           else if x < y then common(xs, y::ys) 
                           else common(x::xs, ys)

它的类型为int list * int list -&gt; int list

要使嵌套列表工作,您可以基于common 的解决方案,沿线:

fun nested_common([]) = []
  | nested_common(x::[]) = x
  | nested_common(x::y::rest) = nested_common(common(x,y)::rest)

类型为int list list -&gt; int list

使用它(在莫斯科 ML):

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

【讨论】:

    猜你喜欢
    • 2020-08-20
    • 2014-01-31
    • 2016-10-19
    • 2012-03-11
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多