2017-10-04 55 views
1

我有2种类型的动物:歧视的工会不推断(和创造)这种类型是什么意思?

type Person(name) = 
    member this.Name: string = name 

type Cat(age) = 
    member this.Age: int = age 

的我 “加入” 的类型:

type Animal = 
| Person of Person 
| Cat of Cat 
| Dog 

当我尝试创建一个Person实例:

let person = new Person("Alex") 

我得到的错误:

Union case Animal.Person: Person -> Animal

The type 'string' is not compatible with the type 'Person'

问:

与构造,

类型Animal.Person应该是人的实例。所以有什么问题?

编辑: 的Visual Studio for Windows不显示错误,但如果你添加更多的源代码,你得到错误 “ '人' 不匹配类型 '动物'”:

[<EntryPoint>] 
let main argv = 
    let person = new Person("Alex") 

    person 
    |> KnowAnimal 
    |> printfn "%O" 
+0

那么你的问题是什么。它不起作用的原因与之前的问题不起作用的原因是一样的。并且适用相同的解决方案。请澄清。 – Gustavo

+0

@Gustavo在我以前的问题和现在的“为什么”中“如何”。 Person是一个具有构造函数的类,Animal.Person类型应该是Person的一个实例。所以有什么问题? –

+0

你确定你显示了正确的代码吗?当我运行你的代码时,我没有收到任何错误消息 - 它工作得很好。 – sepp2k

回答

2

The type Animal.Person should be an instance of Person. So, what's the problem?

首先Animal.Person不是一种类型,Person是一种类型,Animal是一种类型。 Animal.Person是以Person作为参数的Animal类型的一种情况。也就是说,它作为Person -> Animal类型的函数,因此它取值为Person,并返回Animal类型的值。这两种类型之间没有子类型关系。

所以person是类型的值PersonPerson personAnimal类型的值,因为Person需要Person并返回一个Animal