【问题标题】:Standard ML exceptions标准机器学习例外
【发布时间】:2013-08-05 11:42:30
【问题描述】:

我有以下代码:

 - exception Negative of string;
> exn Negative = fn : string -> exn
 - local fun fact 0 =1
            | fact n = n* fact(n-1)
    in
            fun factorial n=
            if n >= 0 then fact n
            else
            raise Negative "Insert a positive number!!!"
            handle Negative msg => 0
    end;

这有什么问题??我得到了错误:

! Toplevel input:
!       handle Negative msg => 0
!                              ^
! Type clash: expression of type
!   int
! cannot have type
!   exn

我该如何解决?如果用户输入负数,我希望函数通过异常返回 0。

我也想知道当用户输入负数时如何显示消息,因为print()返回单位,但函数的其余部分返回int;

【问题讨论】:

    标签: exception standards sml ml


    【解决方案1】:

    raisehandle 的优先级在 SML 中有点奇怪。你把组写成什么

    raise ((Negative "...") handle Negative msg => 0)
    

    因此,您需要在 if 周围添加括号以获得正确的含义。

    另一方面,我不明白你为什么提出异常只是为了立即捕获它。为什么不在else 分支中简单地返回 0?

    编辑:如果要打印一些内容然后返回结果,请使用分号运算符:

    (print "error"; 0)
    

    但是,我强烈建议不要在阶乘函数中这样做。最好将 I/O 和错误处理与基本计算逻辑分开。

    【讨论】:

      【解决方案2】:

      以下是修复代码的多种方法:

      local
        fun fact 0 = 1
          | fact n = n * fact (n-1)
      in
        (* By using the built-in exception Domain *)
        fun factorial n =
            if n < 0 then raise Domain else fact n
      
        (* Or by defining factorial for negative input *)
        fun factorial n =
            if n < 0 then -1 * fact (-n) else fact n
      
        (* Or by extending the type for "no result" *)
        fun factorial n =
            if n < 0 then NONE else SOME (fact n)
      end
      

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 1970-01-01
        • 2021-09-02
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 2013-01-29
        • 2019-01-11
        • 1970-01-01
        相关资源
        最近更新 更多