gpt4 book ai didi

F# 检查算术范围

转载 作者:行者123 更新时间:2023-12-03 12:33:53 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com