我第一次学习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
前两项工作找不到,但我无法让这项工作得到改善。第三个功能的要点是添加二进制数并返回数字列表。
感谢任何帮助。 感谢
答案 0 :(得分:1)
addition
中的错误是One
和Zero
不是列表,因此它们与[]
,ds1
等不兼容。
您与inc
和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))