【问题标题】:Check whether an input is real of integer检查输入是否为整数实数
【发布时间】:2012-09-23 04:34:36
【问题描述】:

我想要求用户输入一个变量并检查它是实数还是整数,并对相应的操作进行两种不同的操作。如果整数则为真,否则为假;

fun realorinteger(n)= if n=int then true else false;

但这绝对行不通。我也试过 if n in int 。

有什么帮助吗?

【问题讨论】:

    标签: sml smlnj


    【解决方案1】:

    你不能这样做。

    类型系统根本不允许一个函数采用多种不同的类型,并根据它是哪种类型来操作。您的函数要么采用int,要么采用real。 (或者两者都需要,但也可以使用strings、lists 等...即是多态的)

    您可以通过创建一个数据类型来伪造它,该数据类型封装可以是整数或实数的值,如下所示:

    datatype intorreal = IVal of int | RVal of real
    

    然后您可以对此类值使用模式匹配来提取所需的数字:

    fun realorinteger (IVal i) = ... (* integer case here *)
      | realorinteger (RVal r) = ... (* real case here *)
    

    然后,此函数将具有 intorreal -> x 类型,其中 x 是右侧表达式的类型。请注意,两种情况下的结果值必须是相同的类型。

    这种函数的一个例子可能是舍入函数:

    fun round (IVal i) = i
      | round (RVal r) = Real.round r
    

    然后这样调用:

    val roundedInt  = round (IVal 6);
    val roundedReal = round (RVal 87.2);
    

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      相关资源
      最近更新 更多