【问题标题】:Correct way of defining option in a type在类型中定义选项的正确方法
【发布时间】:2015-09-16 22:38:15
【问题描述】:

我正在学习 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 }

【问题讨论】:

    标签: f# f#-interactive f#-3.0


    【解决方案1】:

    我不清楚为什么motherfather 被定义为函数,但您可以使用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 }
    

    【讨论】:

    • 谢谢马克!,我已经将母亲和父亲定义为函数,因为我想为每个母亲和父亲设置姓名和年龄,直到我设置为“无”
    • @Reis 你能详细说明一下吗?
    • 一切正常,我刚刚明白了你的想法。我现在对类型有点困惑。谢谢你标记
    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多