如何处理机器学习中除零错误

发布于 2024-12-19 13:59:06 字数 226 浏览 8 评论 0原文

我是机器学习新手。

我需要定义一个以条件表达式作为参数的函数,问题是表达式是否无效,如 "10 div 0 = 0"。我该如何处理这个问题?

例如,函数定义如下:foo exp1 = if (exp1) then ... else...,而exp1"10 div 0 = 0",如何处理这个除法错误。

I am new to ML.

I need to define a function taking an conditional expression as argument, the problem is if the expression is invalid like "10 div 0 = 0". How can I handle this?

For example, the function is defined as following: foo exp1 = if (exp1) then ... else..., and exp1 is "10 div 0 = 0", how to handle this division error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故笙诉离歌 2024-12-26 13:59:06

看起来你想问一下SML中的异常处理机制。

当您调用 10 div 0 时,SML 基础库中的 div 函数会引发 Div 异常。这取决于您是否需要该值来处理异常。在这种情况下,您可以返回 true/false 或选项类型:

(* only catch exception, ignore value *)
fun div_check (x, y) = (
  ignore (x div y);
  false
) handle Div => true

(* catch exception and return option value *)
fun div_check2 (x, y) = (
  SOME (x div y)
) handle Div => NONE

更新:

在这种情况下,编译器不会引发 Div 异常,这真的很奇怪。我建议您定义一个自定义 div 函数并自己引发/处理异常:

exception DivByZero;

(* custom div function: raise DivByZero if y is zero *)
infix my_div;
fun x my_div y =
  if y=0 then raise DivByZero else x div y

fun div_check (x, y) = (
  ignore (x my_div y);
  false
) handle DivByZero => true

fun div_check2 (x, y) = (
  SOME (x my_div y)
) handle DivByZero => NONE

It looks like you want to ask about exception handling mechanism in SML.

The div function in SML basis library raise Div exception when you invoke 10 div 0. It depends on whether you need the value or not to handle the exception. You can either return true/false or option type in this case:

(* only catch exception, ignore value *)
fun div_check (x, y) = (
  ignore (x div y);
  false
) handle Div => true

(* catch exception and return option value *)
fun div_check2 (x, y) = (
  SOME (x div y)
) handle Div => NONE

UPDATE:

It is really weird that the compiler doesn't raise Div exception in this case. I suggest that you define a custom div function and raise/handle exceptions yourself:

exception DivByZero;

(* custom div function: raise DivByZero if y is zero *)
infix my_div;
fun x my_div y =
  if y=0 then raise DivByZero else x div y

fun div_check (x, y) = (
  ignore (x my_div y);
  false
) handle DivByZero => true

fun div_check2 (x, y) = (
  SOME (x my_div y)
) handle DivByZero => NONE
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文