2015-11-12 2 views
2

Почему я не могу добавить None в System.Collections.Generic.Dictionary из Option? Это ожидаемое поведение или ошибка в Mono?F # Словарь опций

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>[email protected]() 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 =() 

Я использую Mono на OS X.

$ 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 
+0

Попробуйте 'let d1 = новый словарь (HashIdentity.Structural)'. – ildjarn

+0

Не работает. –

+1

@ Ming-Tang К сожалению, как отметил Кевин, это желаемое поведение. Regular 'Dictionary <_,_>' 'не принимает' null' как ключи. F # 'Map <_,_> 'с другой стороны работает так, как ожидалось, но я знаю, что это может быть не подходящая замена. –

ответ

5

Его не ошибка. Option < «T> использует атрибут [CompilationRepresentation (CompilationRepresentationFlags.UseNullAsTrueValue), который вызывает Нет, чтобы представить, как нуль.

Так что вы на самом деле добавляют нуль в качестве ключа к словарю, который, как вы знаете, не допускается.

Для справки:

UseNullAsTrueValue:. Разрешить использование нуля как представление для нульарных дискриминаторов в дискриминационном союзе

Дополнительная информация здесь Why is None represented as null?

Смежные вопросы