0

我是第一次学习sml,对模式匹配的语法不太确定。

作为实践,我尝试制作一些关于二进制数的简单程序。

datatype Digit = Zero | One
type Nat = Digit list

fun inc [] = One::[]
| inc (Zero::rest) = (One::rest)
| inc (One::rest) = Zero::inc(rest)

fun dec [] = []
| dec (One::rest) = (Zero::rest)
| dec (Zero::rest) = One::dec(rest)


fun add (ds1, ds2) =
    let 
    fun addition ([],[],Zero) = []
            | addition (ds1, [], Zero) = ds1
            | addition ([], ds2, Zero) = ds2
            | addition (One, Zero, Zero) = (One::ds1)
            | addition (One, Zero, One) = Zero::addition(ds1,ds2,One)
            | addition (Zero, One, Zero) = (One::ds1)
            | addition (Zero, One, One) = Zero::addition(ds1,ds2,One)
            | addition (Zero, Zero, Zero) = (Zero::ds1)
            | addition (Zero, Zero, One) = (One::ds1)
            | addition (One, One, Zero) = Zero::addition(ds1,ds2,One)
            | addition (One, One, One) = One::addition(ds1,ds2,One)
    in
      addition(ds1, ds2, Zero)
    end

前两项工作找到了,但我无法获得额外的工作。第三个函数的重点是添加二进制数并返回一个数字列表。

任何帮助表示赞赏。谢谢

4

1 回答 1

1

错误addition在于OneandZero不是列表,因此它们与[],ds1等不兼容。

inc你用and做得很好dec。我认为您可以使用相同的模式add并利用inc您创建的模式:

fun add (ds1, []) = ds1
  | add ([], ds2) = ds2
  | add (Zero::ds1, d::ds2) = d::add(ds1, fs2)
  | add (One::ds1, Zero::ds2) = One::add(ds1,ds2)
  | add (One::ds1, One::ds2) = Zero::inc(add(ds1,ds2))
于 2012-09-20T19:44:40.753 回答