【问题标题】:In F#, how to update optional nested records?在 F# 中,如何更新可选的嵌套记录?
【发布时间】:2020-11-09 04:44:52
【问题描述】:

(新手问题)。

我一直在努力使用 F# 中的选项更新嵌套记录。这是怎么做到的?

请假设:

module Visit =
    type Model =
        {
            Id: int
            Name: string
        }
    let initWithTime (t:DateTime) =
        {
            Id = 0
            Name = sprintf "Time is %A" t
        }

module Cell =
    type Model =
       {
            Id: int
            Visit: Visit.Model option
       }

let setVisitFromInteger (i:int, m:Model) =
        let appointmentTime = 
            DateTime.Today + TimeSpan.FromMinutes(float i)
        { m with Visit = { m.Visit 
                           match m.Visit with
                           | Some x -> x with Name = sprintf "New appointment time %A" appointmentTime
                           | None -> Visit.initWithTime appointmentTime
                         }
        }

显然,setVisitFromInteger 完全错误。如何正确更新嵌套的可选记录?

TIA

【问题讨论】:

    标签: f#


    【解决方案1】:

    我认为您只是对语法有些困惑。这是一个正确的版本:

    open System
    
    module Visit =
        type Model =
            {
                Id: int
                Name: string
            }
        let initWithTime (t:DateTime) =
            {
                Id = 0
                Name = sprintf "Time is %A" t
            }
    
    module Cell =
        type Model =
           {
                Id: int
                Visit: Visit.Model option
           }
    
    open Cell
    
    let setVisitFromInteger (i:int, m:Model) =
            let appointmentTime = 
                DateTime.Today + TimeSpan.FromMinutes(float i)
            { m with
                Visit =
                    match m.Visit with
                    | Some x ->  { x with Name = sprintf "New appointment time %A" appointmentTime }
                    | None -> Visit.initWithTime appointmentTime
                    |> Some
            }
    

    请注意,记录更新表达式中的Visit 是一个选项,而不是记录,因此它不需要记录语法。但是,模式匹配中需要记录语法,因为您正在尝试执行嵌套记录更新表达式。

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      相关资源
      最近更新 更多