我有以下代码:
datatype complex = RealImg of real * real | Infinity;
fun divisionComplex(RealImg(a, b), RealImg(0.0, 0.0)) = Infinity
fun divisionComplex(RealImg(a, b), RealImg(c, d)) =
RealImg ((a * c + b * d) / (c * c + d * d), ((b * c) - (a * d))/ (c* c + d * d))
但是它失败了:
Error: syntax error: inserting EQUALOP
我很困惑。为什么会这样?我知道我无法比较SML中的两个实数,但是我应该如何用0进行模式匹配?
答案 0 :(得分:2)
正如您所说,SML不允许对实数进行模式匹配,但是建议改用Real.==
或将这些数字之间的差与某个增量进行比较。
仅使用if语句呢? (还添加了一些Infinity
案例只是为了使对函数参数的匹配详尽无遗,但是可以随意更改它,因为它并不假装正确)
datatype complex = RealImg of real * real | Infinity;
fun divisionComplex(Infinity, _) = Infinity
| divisionComplex(_, Infinity) = Infinity
| divisionComplex(RealImg(a, b), RealImg(c, d)) =
if Real.== (c, 0.0) andalso Real.== (d, 0.0)
then Infinity
else
RealImg ((a * c + b * d) / (c * c + d * d), ((b * c) - (a * d))/ (c* c + d * d))