我在以下代码中使用 F# 类型和数据结构(我在 Mac 上使用 Monodevelop,这仅在 Interactive 中发生):
type UnbalancedSet<'a> =
| E
| T of UnbalancedSet<'a> * 'a * UnbalancedSet<'a>
let rec insert x = function
| E -> T(E, x, E)
| T(a, y, b) as s ->
if x < y then T(insert x a, y, b)
elif x > y then T(a, y, insert x b)
else s
它适用于简单类型,如 ints 浮点数和字符,但是当涉及字符串或元组时,它会给出以下错误:
let a = insert (3, 9) E;;
System.TypeInitializationException: An exception was thrown by the type initializer for UnbalancedSet`1 ---> System.NullReferenceException: Object reference not set to an instance of an object
at FSI_0004+UnbalancedSet`1[System.Tuple`2[System.Int32,System.Int32]]..cctor () [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at <StartupCode$FSI_0004>.$FSI_0004.main@ () [0x00000] in <filename unknown>: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) [0x00000] in <filename unknown>:0
Stopped due to error
我不明白发生了什么事。我希望这段代码能够工作,因为类型是可比较的。有什么线索吗?