F# 检查算术范围

标签 f# module scope operators math

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

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

会导致算术溢出异常。

但是如果我想在一些小范围内使用检查算术,比如 C# 允许使用关键字 checked 怎么办? :
int x = 1 + int.MaxValue;             // ok
int y = checked { 1 + int.MaxValue }; // overflow

如何通过打开 Checked 来控制运算符重定义的范围模块或使其尽可能小?

最佳答案

你总是可以定义一个单独的操作符,或者使用阴影,或者使用括号来为临时阴影创建一个内部范围:

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+编译器选项:

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

关于F# 检查算术范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2271198/

相关文章:

c# - F# 类型如何转移到 C#?

java - jdk.dynalink 在 Java 9 的引导类路径中不可见

php - K2_content 模块评级

java - Tomcat 中 System.setProperty 的范围

php - 访问 PHP 函数中的全局变量

asynchronous - F# 异步映射不同类型

函数式编程: Embedding functions in AST?

arrays - F# 两个数组 - 第一个数组乘积按第二个数组上的索引过滤

r - Shiny 的模块 : Accessing and changing reactiveValues situated inside module`s server function from the outside?

JavaScript:如何从原型(prototype)属性上的另一个函数调用原型(prototype)属性上的函数,所有这些都在闭包内?