代码之家  ›  专栏  ›  技术社区  ›  Mankarse

如何在F中显式使用未检查的算术运算符#

f#
  •  3
  • Mankarse  · 技术社区  · 7 年前

    如果我使用 --checked+ 选项编译F#代码时,如何对特定操作使用未检查的算术。

    走另一条路很容易,只要用 FSharp.Core.Operators.Checked 但是我找不到合适的模块来获取未检查的运算符版本。

    这个 FSharp.Core.Operators.Unchecked 模块存在,但不包含任何基本算术运算,例如 + , * 等等。

    例如:

    let a = FSharp.Core.uint32.MaxValue
    let b = a+1u //Alter this to get it to work?
    //b should be 0,
    //rather than OverflowException being thrown in the previous line
    b
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Tomas Petricek    7 年前

    默认未选中的运算符在 Microsoft.FSharp.Core.Operators . 如果您只需要在几个地方使用它,可以通过完整的模块名显式地引用运算符:

    let a = FSharp.Core.uint32.MaxValue
    let b = Microsoft.FSharp.Core.Operators.(+) a 1u
    
        2
  •  2
  •   Gene Belitski    7 年前

    更详细的版本 Tomas' answer 重新定义未选中的添加以继续使用 infix 符号:

    下面的演示程序

    let (+!) x y = Operators.(+) x y
    
    [<EntryPoint>]
    let main argv = 
       try
           let _ = 1 + System.Int32.MaxValue
           printfn "Fine"
       with
           e -> printfn "Exception"
    
       try
           let _ = 1 +! System.Int32.MaxValue
           printfn "Fine"
       with
           e -> printfn "Exception"
       0
    

    正在编译 --checked+ 标记和执行的打印

    Exception
    Fine