首页 > 解决方案 > ML : 匹配非穷举

问题描述

我想让函数命名为headcol

headcol[[1,2],[3,4]] = [1,3]; 

所以我做了这样的功能:

fun headcol [] = [] 
  | headcol [x::xs',y::ys'] = [x,y]

但是当我调用它时,我会得到一个非穷尽的匹配。

标签: smlmlnon-exhaustive-patterns

解决方案


IIUC,headcol将提取参数中的所有列表头,其类型为'a-list-list. 你的数学只是[]and [x::xs', y::ys'],而不是其他任何东西。因此,如果您的论点有 2 个以上的子列表,则 execption 将引发:

- headcol[[1,2],[3,4], [4, 5, 9]]; 

uncaught exception Match [nonexhaustive match failure]
  raised at: a.sml:9.34
- 

如果你只想处理两个元素的列表,pair 是更好的选择。否则,您应该匹配更多案例:

fun headcol list =
    case list of
        [] => []
      | x::xs' =>
        case x of
            [] => headcol xs'
         |  h::t => h::(headcol xs')

输出:

- headcol[[1,2],[3,4], [4, 5, 9]]; 
- val it = [1,3,4] : int list

推荐阅读