【问题标题】:Can't unify IEEEReal.rounding_mode with real无法将 IEEEReal.rounding_mode 与 real 统一
【发布时间】:2016-08-22 02:37:37
【问题描述】:

当我尝试像这样将实数转换为整数时,为什么会出错?

fun stuff a  =
  Real.toInt a

错误:

Error-Can't unify IEEEReal.rounding_mode with real (Different type constructors) Found near stuff
(0.0)

【问题讨论】:

    标签: floating-point integer type-conversion sml


    【解决方案1】:

    也许你忽略了Real.toInt : IEEEReal.rounding_mode -> real -> int,即接受一个额外的参数来指定how rounding is made。如果您不想指定这个额外的参数,例如喜欢

    fun round x = Real.toInt IEEEReal.TO_NEAREST x
    

    你可以使用其中一种功能

    • Real.floor : real -> int 假定为 IEEEReal.TO_NEGINF
    • Real.ceil : real -> int 假定为 IEEEReal.TO_POSINF
    • Real.trunc : real -> int 假定为 IEEEReal.TO_ZERO,或
    • Real.round : real -> int 假定为 IEEEReal.TO_NEAREST

    有趣的事实:函数Real.toIntactually defined in terms of these four functions

    【讨论】:

    • 有时 SML 是不必要的迂腐。我认为这是其中一种情况,但事实就是如此。
    • 尤其是如果您要转换的真实值已经以 .0 结尾...但我猜计算机不知道这一点?
    • @lotolmencre SML 非常重视具有非常清晰的语义。它是为数不多的真正具有形式语义的语言之一(相对于形式语法与不太形式语义相结合的形式)。这允许编写代码以便证明是正确的。作为代价的一部分,它迫使程序员对其他语言中隐含的东西更加明确。
    • @lotolmencre:在编译时很难知道 real 是否以 .0 结尾。在 floatint 类型之间动态转换的语言也不会,它们通常甚至会假设您想要舍入的方式。如果知道这个数字总是以.0结尾,那么就没有理由使用实数来表示它,是吗?确定一个 real 是否以 .0 结尾并不是一件小事due to imprecision。假设它总是以 .0 结尾,但是将它从 real 转换为 int,听起来像是 Real.trunc 的工作。
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多