在 SML 中将字符串转换为实数

发布于 2025-01-04 00:49:44 字数 114 浏览 5 评论 0原文

我想将实数的字符串表示形式转换为实数类型。 我知道我可以执行 Real.fromString("5.5") 但它不会返回实数类型,而是返回实数选项类型,我无法将其与任何其他实数相乘或相加。

I want to convert string representation of real number to real type.
I know that I can do Real.fromString("5.5") but it doesn't return real type but real option type which I can't multiply or add with any other real.

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

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

发布评论

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

评论(2

马蹄踏│碎落叶 2025-01-11 00:49:44

通过模式匹配或使用 Option 结构中的函数之一从选项中提取值。例如:

- val x = Real.fromString("5.5");
> val x = SOME 5.5 : real option
- Option.getOpt(x, 0.0);
> val it = 5.5 : real

Extract the value from the option by pattern matching or using one of the functions in the Option structure. For example:

- val x = Real.fromString("5.5");
> val x = SOME 5.5 : real option
- Option.getOpt(x, 0.0);
> val it = 5.5 : real
内心荒芜 2025-01-11 00:49:44

为了补充 Michael J. Barber 的答案,选项类型是一种代数数据类型,要么是某些东西,要么是无。

通常,在机器学习中,我们通常使用模式匹配来解构代数数据类型:

case Real.fromString "5.5" of SOME x => x + 1.0
                            | NONE   => 42.0; 

您可以像 Michael J. Barber 建议的那样使用 getOpt (您实际上不需要 Option.,因为 >getOpt 是在顶级环境中),这是上面的简化版本。

或者,如果您确定它将是 SOME,则可以使用 valOf (如果为 NONE,则会出错):

- val x = Real.fromString "5.5";
val x = SOME 5.5 : real option
- valOf x;
val it = 5.5 : real

或者您可以在 val 中对其进行模式匹配 (因为 val 也是一种模式匹配,尽管只有一个分支):

- val SOME x = Real.fromString "5.5";
> val x = 5.5 : real

To add to Michael J. Barber's answer, the option type is an algebraic datatype which is either SOME something, or NONE.

Usually, in ML we usually deconstruct algebraic datatypes with pattern matching:

case Real.fromString "5.5" of SOME x => x + 1.0
                            | NONE   => 42.0; 

You could use getOpt like Michael J. Barber suggested (you don't actually need the Option. since getOpt is in the top-level environment), which is a simplified version of the above.

Or, if you are sure that it is going to be a SOME, you could use valOf (which will error if it is NONE):

- val x = Real.fromString "5.5";
val x = SOME 5.5 : real option
- valOf x;
val it = 5.5 : real

or you could pattern-match it away in a val (since val is also a pattern match, albeit with only one branch):

- val SOME x = Real.fromString "5.5";
> val x = 5.5 : real
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文