在类型中定义选项的正确方法
Correct way of defining option in a type
我正在学习 F# 并尝试创建一个名为 Person 的类型,它具有 4 个属性。其中 2 个(母亲和父亲)是可选的,但不知何故我收到编译器错误。
type Person = {
name : string;
age : int;
mother: Person option -> Person option;
father: Person option -> Person option;
}
let defaultPerson = {
name = "";
age = 0;
mother = fun person -> person;
father = fun person -> person }
let displayPerson person =
printfn "Name: %s, Age: %d" person.name person.age
let setName person name =
{ person with Person.name = name }
let setAge person name =
{ person with Person.name = name }
let setMother person mother =
{ person with Person.mother = mother }
let setFather person father =
{ person with Person.father = father }
但是当我尝试下面的代码时,它抛出一个编译器错误:
let mother1 = {
Person.name = "Angelica";
age = 47;
mother = Option<Person>.None; //mother = None doesn't work
father = Option<Person>.None }
我不清楚为什么 mother
和 father
被定义为 函数 ,但您可以使用 fun
关键字设置它们,正如您似乎已经发现的那样:
let mother1 = {
Person.name = "Angelica";
age = 47;
mother = fun _ -> None;
father = fun _ -> None }
以下是 Person
更合理的定义吗?
type Person' = {
Name : string;
Age : int;
Mother: Person' option;
Father: Person' option;
}
这样您就可以定义这样的值:
let mother2 = {
Name = "Angelica";
Age = 47;
Mother = None;
Father = None }
我正在学习 F# 并尝试创建一个名为 Person 的类型,它具有 4 个属性。其中 2 个(母亲和父亲)是可选的,但不知何故我收到编译器错误。
type Person = {
name : string;
age : int;
mother: Person option -> Person option;
father: Person option -> Person option;
}
let defaultPerson = {
name = "";
age = 0;
mother = fun person -> person;
father = fun person -> person }
let displayPerson person =
printfn "Name: %s, Age: %d" person.name person.age
let setName person name =
{ person with Person.name = name }
let setAge person name =
{ person with Person.name = name }
let setMother person mother =
{ person with Person.mother = mother }
let setFather person father =
{ person with Person.father = father }
但是当我尝试下面的代码时,它抛出一个编译器错误:
let mother1 = {
Person.name = "Angelica";
age = 47;
mother = Option<Person>.None; //mother = None doesn't work
father = Option<Person>.None }
我不清楚为什么 mother
和 father
被定义为 函数 ,但您可以使用 fun
关键字设置它们,正如您似乎已经发现的那样:
let mother1 = {
Person.name = "Angelica";
age = 47;
mother = fun _ -> None;
father = fun _ -> None }
以下是 Person
更合理的定义吗?
type Person' = {
Name : string;
Age : int;
Mother: Person' option;
Father: Person' option;
}
这样您就可以定义这样的值:
let mother2 = {
Name = "Angelica";
Age = 47;
Mother = None;
Father = None }