4 people like it.

Why printing None prints

When printing None via printfn (or any of the other print functions for that matter), the result is . This example shows why.

Printing None results in <null>

1: 
2: 
None |> printfn "Value: %A"
// Value: <null>

Custom implementation of Option&lt;'T&gt; - Printing None results in None

1: 
2: 
3: 
4: 
5: 
6: 
type MyOption<'T> =
| Some of 'T
| None

MyOption.None |> printfn "Value: %A"
// Value: None

Revised MyOption&lt;'T&gt; - Printing None results in &lt;null&gt;

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
// Here, MyOption2<'T> is decorated with CompilationRepresentationAttribute and
// the UseNullAsTrueValue flag is set just like it is for Option<'T> in the F#
// library. This is how None is represented in the compiled code.
// See http://bit.ly/1cA0QfS for more info about CompilationRepresentation
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type MyOption2<'T> =
| Some of 'T
| None

MyOption2.None |> printfn "Value: %A"
// Value: <null>
union case Option.None: Option<'T>
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
type MyOption<'T> =
  | Some of 'T
  | None

Full name: Script.MyOption<_>
union case MyOption.Some: 'T -> MyOption<'T>
union case MyOption.None: MyOption<'T>
Multiple items
type CompilationRepresentationAttribute =
  inherit Attribute
  new : flags:CompilationRepresentationFlags -> CompilationRepresentationAttribute
  member Flags : CompilationRepresentationFlags

Full name: Microsoft.FSharp.Core.CompilationRepresentationAttribute

--------------------
new : flags:CompilationRepresentationFlags -> CompilationRepresentationAttribute
type CompilationRepresentationFlags =
  | None = 0
  | Static = 1
  | Instance = 2
  | ModuleSuffix = 4
  | UseNullAsTrueValue = 8
  | Event = 16

Full name: Microsoft.FSharp.Core.CompilationRepresentationFlags
CompilationRepresentationFlags.UseNullAsTrueValue: CompilationRepresentationFlags = 8
type MyOption2<'T> =
  | Some of 'T
  | None

Full name: Script.MyOption2<_>
union case MyOption2.Some: 'T -> MyOption2<'T>
union case MyOption2.None: MyOption2<'T>
Raw view Test code New version

More information

Link:http://fssnip.net/kL
Posted:11 years ago
Author:Dave Fancher
Tags: option , compilationrepresentationattribute