【问题标题】:SML Manipulating Elements in a Nested ListSML 操作嵌套列表中的元素
【发布时间】:2021-01-20 21:36:24
【问题描述】:

我希望能够操作嵌套列表中的项目,例如[[1,2,3],[4,5],[6,7]]

fun f (nil, _) = nil 

|   f((a :: b), rest) = a;

我写上面只是为了能够访问第一个列表中的第一个元素,但它给出了这个错误

stdIn:29.1-29.28 Error: operator and operand do not agree [tycon mismatch]

operator domain: 'Z list list * 'Y

operand:         'X[INT] list list

我尝试了其他几种方法,但我就是不明白出了什么问题。

【问题讨论】:

  • nil 是一个列表 - 而不是 int - 所有子句都必须产生相同类型的值。了解option 类型。

标签: sml


【解决方案1】:

访问第一个列表中的第一个元素

因为没有问题,所以很难回答。但这一点就像一个斗争点。在不确切知道您想要实现什么的情况下,以下是一些对列表进行操作的函数示例:


fun firsts [] = []
  | firsts ([]::rest) = firsts rest
  | firsts ((x::xs)::rest) = x :: firsts rest

试试这个:

- firsts [[1,2,3],[4,5],[6,7]];
> val it = [1, 4, 6] : int list

它的工作方式是在列表的空列表上,没有更多的第一个元素,因此返回第一个元素的空列表; first [] = []。在这些内部列表中的第一个为空的列表列表中,该列表没有第一个元素,因此找到剩余列表的第一个元素first ([]::rest) = firsts rest。最后,对于第一个非空列表的非空列表,该列表的第一个元素x 是最终结果的一部分。

你可以把这个函数写成:

fun firsts rest = List.map head rest

但是由于head 在空列表上崩溃(函数是部分的),这就像省略了中间模式。承认 head 是部分的并提供更安全的“无结果”值,您可以在没有错误的情况下获得非常相似的结果:

fun safeHead [] = NONE
  | safeHead (x::xs) = SOME x

fun firsts rest = List.mapPartial safeHead rest

试试这个:

- firsts [[1,2,3],[],[4,5],[6,7,8],[],[],[9]];
> val it = [1, 4, 6, 9] : int list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2022-01-06
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2013-12-18
    相关资源
    最近更新 更多