【发布时间】:2016-06-14 05:04:36
【问题描述】:
我定义了不同的类型:
type TypeNull() = class end
type MyType1 = {
a:int;
b:int
}
type MyType2 = {
a:string;
b:int
}
type MyType3 = {
a:string;
b:DateTime
}
以及使用它们的不同的有区别的工会:
type myDU =
| A of int
| B of string
| C of string
type myDU2 =
| D of MyType1
| E of MyType2
| F of TypeNull
我有将 myDU 映射到 myDU2 的函数:
let applyArray = function
| A x -> [E({a="1"; b=2})]
| B x -> [D({a=1; b=2});E({a="1"; b=2});E({a="5"; b=24})]
| C x -> [D({a=1; b=2});E({a="1"; b=2});F(TypeNull())]
然后是两个测试来测试相等性:
let arrayValueEquals =
let expected = [D({a=1; b=2});E({a="1"; b=2});E({a="5"; b=24})]
let actual = applyArray <| B("xxx")
actual = expected
let arrayValueNullEquals =
let expected = [D({a=1; b=2});E({a="1"; b=2});F(TypeNull())]
let actual = applyArray <| C("xxx")
actual = expected
fsi 给出的内容:
val applyArray : _arg1:myDU -> myDU2 list
val arrayValueEquals : bool = true
val arrayValueNullEquals : bool = false
我的问题如下,为什么第一次测试成功,第二次失败?
这里是完整的要点:
// Learn more about F# at http://fsharp.net. See the 'F# Tutorial' project
// for more guidance on F# programming.
#load "Library1.fs"
open test2
open System
type TypeNull() = class end
type MyType1 = {
a:int;
b:int
}
type MyType2 = {
a:string;
b:int
}
type MyType3 = {
a:string;
b:DateTime
}
type myDU =
| A of int
| B of string
| C of string
type myDU2 =
| D of MyType1
| E of MyType2
| F of TypeNull
let applyArray = function
| A x -> [E({a="1"; b=2})]
| B x -> [D({a=1; b=2});E({a="1"; b=2});E({a="5"; b=24})]
| C x -> [D({a=1; b=2});E({a="1"; b=2});F(TypeNull())]
let arrayValueEquals =
let expected = [D({a=1; b=2});E({a="1"; b=2});E({a="5"; b=24})]
let actual = applyArray <| B("xxx")
actual = expected
let arrayValueNullEquals =
let expected = [D({a=1; b=2});E({a="1"; b=2});F(TypeNull())]
let actual = applyArray <| C("xxx")
actual = expected
【问题讨论】:
-
您是否打印出
actual的值来查看它是什么?我怀疑 TypeNull() 不是你想象的那样。或者您是否尝试将预期和实际发送到 F# Interactive 以查看类型。 -
它确实给了我:> TypeNull();;验证它:TypeNull = FSI_0002+TypeNull
-
> 让实际 = applyArray
标签: f# equality discriminated-union