2016-11-15 86 views
1

我感到有点糊涂了“匹配冗余”的错误运行下面的代码时,我得到:为什么我得到“匹配redudant”错误?

datatype expression = Constant of int | 
      Variable of string | 
      Operator of string * expression | 
      Pair of expression list | 
      List of expression list 

fun add2 (ul1: expression, ul2: expression) = 
    let 
     fun gcd (a, b) = 
      if a >= b 
      then 
       if (a mod b) = 0 
       then b 
       else gcd (b,(a mod b)) 
      else 
      if (b mod a) = 0 
      then a 
      else gcd (a, (b mod a)) 
     fun lcm (a,b) = 
      a*b div (gcd(a,b))  
    in 

     case ul1 of 
      Operator("/",Pair [Constant a, Constant b]) => 
       case ul2 of 
        Operator("/",Pair [Constant c, Constant d]) => 
        a*d + c*b//(b*d) 
        |Operator("/",Pair [Variable c, Constant d])=> 
        Operator("/",Pair [(Operator("+", Pair [Constant a, Variable c])),Constant (lcm(b,d))]) 

      |Operator("/",Pair [Variable a, Constant b]) => 
       case ul2 of 
        Operator("/",Pair [Constant c, Constant d]) => 
        Operator("/",Pair [(Operator("+", Pair [Variable a, Constant c])),Constant (lcm(b,d))]) 
        |Operator("/",Pair [Variable c, Constant d])=> 
        Operator("/",Pair [(Operator("+", Pair [Variable a, Variable c])),Constant (lcm(b,d))]) 


    end 

确切的错误按摩:

C:\Users\erikj\Dropbox\Fakulteta Laptop\Programiranje\domacanaloga 6.sml:91.5-102.93 Error: match redundant and nonexhaustive 
      Operator ("/",Pair (Constant c :: Constant d :: nil)) => ... 
      Operator ("/",Pair (Variable c :: Constant d :: nil)) => ... 
    --> Operator ("/",Pair (Variable a :: Constant b :: nil)) => ... 

我不介意关于非详尽比赛因为它只是一个练习。 非常感谢您的帮助!

+0

最后两种情况不是相同的吗?我不知道SML,但看起来像构造函数匹配,最后2行使用'Variable'和'Constant'。 – Carcigenicate

+0

最后两行你确切的意思?内部“情况”在两种情况下都与ul2相同,但您可以通过ul1的不同分支进行分析。我不明白为什么你会遇到冗余问题,如果你有这样的事情,因为每个外部案例都应该有它自己的环境吗?或者我只是在我的脑海里错误地设置了一些东西。在这种情况下,这个例子有一个简单的解决方法吗? – Amuoeba

回答

1

考虑下面的代码:

case ul1 of 
    Operator("/",Pair [Constant a, Constant b]) => 
     case ul2 of 
      Operator("/",Pair [Constant c, Constant d]) => 
      ... 
      |Operator("/",Pair [Variable c, Constant d])=> (* Case A *) 
      ... 
      |Operator("/",Pair [Variable a, Constant b]) => (* Case B *) 
      ... 

它应该很清楚这种情况下,B是多余的,因为它是相同的情况下的(除了变量名)。

这段代码和你的代码之间唯一的变化是我改变了case B的缩进。现在缩进并不影响SML程序的语义,所以case B在代码中和你在这里一样冗余。

对于读者来说,从缩进中可以明显地看出,你的情况B属于外部模式匹配,但正如我所说的,编译器不关心缩进,所以你需要使用圆括号或开始结束块来告诉编译器内部匹配结束的地方。

+0

啊是的括号,非常感谢你:) – Amuoeba