【问题标题】:Solving warnings like match non exhaustive and calling polyequal in SML/NJ在 SML/NJ 中解决匹配非穷举和调用 polyequal 等警告
【发布时间】:2012-09-22 19:22:00
【问题描述】:

问题是输入两个列表并根据另一个列表中的相应编号重复第一个列表中的元素。 例如repeat([2,3,4],[1,2,2]) 会给[2,3,3,4,4]

fun repeat1(a,b)=if b>0 then a::repeat1(a,b-1) else [];
fun repeat([],[])=[]
|repeat([l1],[m1])=repeat1(l1,m1)
|repeat(l1::ln,m1::mn)=if length(l1::ln)=length(m1::mn) then if ln<>[] then repeat1(l1,m1)@repeat(ln,mn) else [] else []; 

错误提示

stdIn:36.64-36.66 Warning: calling polyEqual
stdIn:34.5-36.112 Warning: match nonexhaustive
          (nil,nil) => ...
          (l1 :: nil,m1 :: nil) => ...
          (l1 :: ln,m1 :: mn) => ...

这些是做什么用的(我知道它对于基本案例和归纳案例是不够的)?但是,即使这不会影响程序的输出,我该如何删除此警告?谢谢。

【问题讨论】:

    标签: pattern-matching sml smlnj


    【解决方案1】:

    当两个列表中只有一个为空时,您显然忘记了两个基本情况。由于这些情况是格式错误的输入,您可以使用异常来处理它们:

    exception LengthNotEqual
    
    fun repeat ([], []) = []
      | repeat ([], _) = raise LengthNotEqual
      | repeat (_, []) = raise LengthNotEqual
      | ...
    

    添加两个新的基本情况后,您不再需要比较最后一个模式中两个列表的长度。应该避免使用length,因为它会再次遍历整个列表。由于冗余,模式([l1], [m1]) 可以被删除。

    所以新的repeat 函数看起来像:

    fun repeat ([], []) = []
      | repeat ([], _) = raise LengthNotEqual
      | repeat (_, []) = raise LengthNotEqual
      | repeat (l1::ln, m1::mn) = repeat1(l1, m1)@repeat(ln, mn)
    

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多