【问题标题】:SML: How to determine if a list index is empty?SML:如何判断一个列表索引是否为空?
【发布时间】:2019-03-24 16:54:58
【问题描述】:

我正在尝试确定我的 hd(tl list) 是否为空。 hd(tl list) = ?我会在等号的另一边使用什么?

【问题讨论】:

  • 您可以将tl list[] 进行比较:tl list = []
  • “列表索引为空”是什么意思?
  • @John Coleman 谢谢!那行得通。

标签: list functional-programming sml smlnj


【解决方案1】:

您可以将问题'is hd(tl list) nothing or not'表达为等效的问题,'list 是否有少于两个元素'。后一个问题很容易通过 SML 以优雅的方式使用列表中的模式匹配来回答。这是一个交互式会话:

$ poly
Poly/ML 5.7.1 Release
> fun isNothing [] = true
#   | isNothing [_] = true
#   | isNothing _ = false;
val isNothing = fn: 'a list -> bool

这个函数的意思是,'一个空列表计算为true','一个具有单个元素的列表计算为true',任何其他列表计算为false。测试:

> isNothing [];
val it = true: bool
> isNothing [1];
val it = true: bool
> isNothing [1, 2];
val it = false: bool
> isNothing [1, 2, 3];
val it = false: bool

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 2013-03-11
    • 1970-01-01
    • 2012-03-15
    • 2014-07-18
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多