sml中是否有内置的整数函数?
我的意思是:
我必须从文件中读取一个数字,如果它是整数则显示为输出,如果数字不是整数则引发异常。例如,我必须检查(Int.fromString())的输出是否为整数,如果是...则显示它(重复上面)
答案 0 :(得分:1)
类型系统将确保给出函数的值的类型与函数的类型签名匹配。
也就是说,如果你有一个以整数作为输入的函数,比如
fun double n = 2 * n
(* this function has type: int -> int *)
然后n
将始终为整数。使用除整数之外的任何东西都不可能调用该函数;它会给出类型错误。
如果您有多态函数,例如
fun pair n = (n, n)
(* this function has type: 'a -> 'a * 'a *)
然后您无法知道输入在运行时的类型。所有类型的输入都将被视为相同。
但是,通过在定义函数时使类型显式化,您可以始终将多态函数限制为仅对给定类型起作用:
fun pairInt (n : int) = (n, n)
(* this function has type: int -> int * int *)
通过比较从调用pair
到pairInt
,pair 5
到{{1}的内容,您可以看到pairInt 5
和pair "foo"
之间的区别}。
如果您有pairInt "foo"
,如果您尝试使用int option
将string
转换为int
,则可以提取Int.fromString
在几个方面。有关如何执行此操作,我建议您使用问题“In smlnj how do you convert “string option” to “string”?”。