Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Conversion F# Script vs. Compiled F#

In the F# Interactive, the following piece of code works:

> printfn "%A" (decimal 1I)
1M

However, in a compiled F# program, an error message appears:

The type 'Numerics.BigInteger' does not support a conversion to the type 'decimal'

What happened there? Is it because the different set of references (and versions of references) are used between F# versions? or the internal representations of the decimal are different across compiled and interpreted modes.

like image 974
Ming-Tang Avatar asked Nov 08 '11 01:11

Ming-Tang


2 Answers

This is likely because your F# compiled program is targeting the .NET Framework 2.0 / F# 2.0. The F# interactive is using .NET Framework 4.0 / F# 4.0.

The 2.0 Framework uses the BigInteger in FSharp.Core. The 4.0 Framework uses System.Numerics.BigInteger. The FSharp.Core one does not have the conversion to decimal.

Change your project to target .NET 4.0 and add a reference to System.Numerics and everything should match up.

like image 152
vcsjones Avatar answered Oct 12 '22 10:10

vcsjones


You're right that there is some inconsistency in whether BigInteger can be converted using the decimal function or not. It seems to depend on the version of .NET that you're compiling for. If you're using the F# compiler (or F# interactive) from Visual Studio 2010, then the default target is .NET 4.0. For that target, the compilation works fine:

C:\Temp>"C:\Program Files (x86)\Microsoft F#\v4.0\Fsc.exe" test.fs
Microsoft (R) F# 3.0 Compiler build 2.0.0.0
Copyright (c) Microsoft Corporation. All Rights Reserved.

You can change the target framework by explicitly referencing .NET 2.0 version of mscorlib.dll and FSharp.Core.dll. Then the compiler reports the error you described:

C:\Temp>"C:\Program Files (x86)\Microsoft F#\v4.0\Fsc.exe" test.fs --noframework 
  -r:C:\Program Files (x86)\FSharp-2.0.0.0\bin\FSharp.Core.dll 
  -r:C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
Microsoft (R) F# 3.0 Compiler build 2.0.0.0
Copyright (c) Microsoft Corporation. All Rights Reserved.

test.fs(1,23): error FS0001: The type 'System.Numerics.BigInteger' does not support 
  a conversion to the type 'decimal'

If you're getting the error when compiling the project, then your project is probably configured to compile for .NET 2.0.

like image 30
Tomas Petricek Avatar answered Oct 12 '22 09:10

Tomas Petricek