F# 选项字典

F# Dictionary of Options

为什么我不能将 None 添加到 OptionSystem.Collections.Generic.Dictionary?这是预期的行为还是 Mono 中的错误?

F# Interactive for F# 3.1 (Open Source Edition)
Freely distributed under the Apache 2.0 Open Source License

For help type #help;;

> open System.Collections.Generic;;
> let d1 = new Dictionary<int option, int>();;

val d1 : Dictionary<int option,int> = dict []

> d1.Add(None, 1);;
System.ArgumentNullException: Value cannot be null.
Parameter name: key
   at System.ThrowHelper.ThrowArgumentNullException (ExceptionArgument argument) in <filename unknown>:line 0
   at System.Collections.Generic.Dictionary`2[TKey,TValue].Insert (System.Collections.Generic.TKey key, System.Collections.Generic.TValue value, Boolean add) in <filename unknown>:line 0
   at System.Collections.Generic.Dictionary`2[TKey,TValue].Add (System.Collections.Generic.TKey key, System.Collections.Generic.TValue value) in <filename unknown>:line 0
   at <StartupCode$FSI_0004>.$FSI_0004.main@ () in <filename unknown>:line 0
   at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
   at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) in <filename unknown>:line 0
Stopped due to error
> d1.Add(Some 10, 1);;
val it : unit = ()

我在 OS X 上使用 Mono。

$ mono --version
Mono JIT compiler version 4.2.0 (Stable 4.2.0.179/a224653 Tue Oct  6 11:28:25 PDT 2015)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           normal
    SIGSEGV:       altstack
    Notification:  kqueue
    Architecture:  amd64
    Disabled:      none
    Misc:          softdebug
    LLVM:          supported, not enabled.
    GC:            sgen

这不是错误。 Option<'T> 使用属性 [CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue) 导致 None 表示为 null。

所以你实际上是在字典中添加一个 null 作为键,你知道这是不允许的。

供参考:

UseNullAsTrueValue: Permit the use of null as a representation for nullary discriminators in a discriminated union.

这里有更多信息Why is None represented as null?