【问题标题】:keeping maxInt in a variable (Standard ML)将 maxInt 保存在变量中(标准 ML)
【发布时间】:2023-03-06 05:30:02
【问题描述】:

如何将Integer的最大值放入SML中的val中? 我看到你可以使用intMax

> Int.maxInt;
val it = SOME 1073741823 : int option

但如果我尝试将其作为值放入val,它将打印错误:

> val max:int = Int.maxInt;
Error: pattern and expression in val dec don't agree [tycon mismatch]
pattern:    int
expression:    int option
in declaration:
max : int = Int.maxInt

虽然val max = Int.maxInt 有效,但它使:val max = SOME 1073741823 : int option

我希望变量是 int 类型而不是 int option

换句话说,输出应该是:

> val max = 1073741823 : int

编辑:

感谢您的回答。是否可以设置大于 maxInt 的值? 我要计算:

fun someCalculation num = ceil((Math.sqrt(1.0+8.0*real(num))-1.0)/2.0);
val max_int = Option.valOf Int.maxInt;
val current = someCalculation max_value;

因为8.0*real(maxInt) 它不起作用。是否可以计算?请注意,最终答案不大于 maxInt。

【问题讨论】:

  • 如果您的问题是关于其他问题,请提出一个新问题并考虑您想问什么,这样您就不必一直更改它。 :-)

标签: sml ml


【解决方案1】:

如何将Integer的最大值放入SML中的val中?

您可以使用Option.valOf : 'a option -> 'a 删除“选项”部分:

- val max = valOf Int.maxInt;
> val max = 1073741823 : int

使用valOf 通常是不安全的,因为valOf NONE 会引发异常:

- valOf NONE;
! Uncaught exception:
! Option

只有当您的编译器的未来版本附带任意大小的Int 模块时才会发生这种情况。由于 SML/NJ 已经将 IntInf 作为单独的模块,因此这可能不会立即发生。

是否可以设置大于 maxInt 的值?

不使用 int(太小):

- valOf Int.maxInt + 1;
! Uncaught exception:
! Overflow

并且不使用真实(太不精确):

- Real.== (real (valOf Int.maxInt) + 1.0,
           real (valOf Int.maxInt));
> val it = true : bool

但是使用IntInf 库,是的:

- IntInf.maxInt;
> val it = NONE : int option

- IntInf.fromInt (valOf Int.maxInt) * 8;
> val it = 8589934584 : IntInf.int

如您所见,SML/NJ 重载整数文字,因此它们既可以作为 int(阅读:Int31.int)也可以作为 IntInf.int。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2013-04-05
    • 2021-05-20
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多