如何在Standard ML中将Integer最大值存入val变量?
int Type in SML Great question! Let's break down what's happening and how to fix this.
First, the reason you're getting that type mismatch error is because Int.maxInt returns an int option type, not a straight int. The option type here is SML's way of saying "this value might exist (wrapped in SOME) or might not (represented as NONE)—since some SML implementations don't have a fixed maximum integer size.
To get the actual int value out of Int.maxInt, you have two common, straightforward approaches:
1. Use valOf to extract the value from the option
You can use the valOf function, which takes a SOME x and returns the underlying x, giving you the int type you want:
val max = valOf Int.maxInt;
This will output:
val max = 1073741823 : int
A quick note: if Int.maxInt were NONE (unlikely in most standard, fixed-size integer implementations), valOf would throw a runtime error. But for the system you're using (where Int.maxInt returns SOME 1073741823), this is completely safe.
2. Pattern match directly in the val declaration
Another clean way is to pattern match against the SOME constructor right when you declare the variable. This directly binds the underlying integer to your max variable:
val SOME max = Int.maxInt;
This will give you the same result as the valOf method. Just like before, this would fail at runtime only if Int.maxInt were NONE—which isn't a case you need to worry about here.
To recap why your original attempts didn't work:
- When you wrote
val max:int = Int.maxInt;, you tried to assign anint optionvalue to a variable explicitly declared asint—SML's strict type system catches this mismatch to prevent potential bugs. - When you omitted the type annotation,
maxwas correctly typed asint option, which isn't theinttype you were aiming for.
内容的提问来源于stack exchange,提问作者verrrilog

