F#校验算法范围

编程入门 行业动态 更新时间:2024-10-14 14:14:51
本文介绍了F#校验算法范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

F#允许通过打开Checked模块来使用检查的算术,该模块将标准运算符重新定义为要检查的运算符,例如:

F# allows to use checked arithmetics by opening Checked module, which redefines standard operators to be checked operators, for example:

open Checked let x = 1 + System.Int32.MaxValue // overflow

将导致算术溢出异常.

但是,如果我想在较小的范围内使用检查的算术,例如C#允许使用关键字checked:

But what if I want to use checked arithmetics in some small scope, like C# allows with keyword checked:

int x = 1 + int.MaxValue; // ok int y = checked { 1 + int.MaxValue }; // overflow

如何通过打开Checked模块来控制操作符的重新定义范围或使其更小?

How can I control the scope of operators redefinition by opening Checked module or make it smaller as possible?

推荐答案

您始终可以定义一个单独的运算符,或者使用阴影,或者使用parens为临时阴影创建内部范围:

You can always define a separate operator, or use shadowing, or use parens to create an inner scope for temporary shadowing:

let f() = // define a separate operator let (+.) x y = Checked.(+) x y try let x = 1 +. System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" // shadow (+) let (+) x y = Checked.(+) x y try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" // shadow it back again let (+) x y = Operators.(+) x y try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" // use parens to create a scope ( // shadow inside let (+) x y = Checked.(+) x y try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" ) // shadowing scope expires try let x = 1 + System.Int32.MaxValue printfn "ran ok" with e -> printfn "exception" f() // output: // exception // ran ok // exception // ran ok // exception // ran ok

最后,另请参见--checked+编译器选项:

Finally, see also the --checked+ compiler option:

msdn.microsoft/en -us/library/dd233171(VS.100).aspx

更多推荐

F#校验算法范围

本文发布于:2023-11-29 20:03:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647486.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!