F# 检查算术范围 [英] F# Checked Arithmetics Scope

查看:17
本文介绍了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?

推荐答案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆