F#校验算法范围 [英] F# Checked Arithmetics Scope
问题描述
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:
http://msdn.microsoft.com/en -us/library/dd233171(VS.100).aspx
这篇关于F#校验算法范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!