Reputation:
I am learning F# and trying to create a type called Person with 4 properties. 2 of them (mother and father) are optional but somehow I am receiving compiler error.
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 }
But when I try following code, it throws a compiler error:
let mother1 = {
Person.name = "Angelica";
age = 47;
mother = Option<Person>.None; //mother = None doesn't work
father = Option<Person>.None }
Upvotes: 3
Views: 69
Reputation: 233150
It's not clear to me why mother
and father
are defined as functions, but you can set them using the fun
keyword, as you already seem to have discovered:
let mother1 = {
Person.name = "Angelica";
age = 47;
mother = fun _ -> None;
father = fun _ -> None }
Wouldn't the following be a more sensible definition of Person
?
type Person' = {
Name : string;
Age : int;
Mother: Person' option;
Father: Person' option;
}
This would let you define a value like this:
let mother2 = {
Name = "Angelica";
Age = 47;
Mother = None;
Father = None }
Upvotes: 3