代码之家  ›  专栏  ›  技术社区  ›  SantiClaus

如何在特定字段上使用map.tryfind?

f#
  •  -1
  • SantiClaus  · 技术社区  · 8 年前

    所以我将数据映射到一个记录,它显示在底部。但问题是下面指定的代码行。我试图用Map.TryFind函数来索引一张地图并在该地图中返回一个字段,但是它正在输出错误:

    Practice2.fsx(299,49): error FS0039: The field, constructor or member 'GrossIncome' is not defined.
    

    我怎样才能成功地做到这一点呢?所用类型的代码如下。

    type GeneralInfo =
        { State : State
          GrossIncome : int }
    
    type FamilyFile = 
        { State : State
          Pets : int
          NumberofChildren : int
          NumberofMembers : int }
    
    type AllData = 
        { State = State
          Month = Month
          Pets  = int
          Children = int
          GrossIncome = int Option }
    

    实例 familyMap generalMap :

    let generalinfo =
       GeneralCsv.GetSample().Rows
        |> Seq.map (fun row -> 
            { State = row.State |> State
              GrossIncome = row.income })
    
    let generalMap =
        generalinfo
        |> Seq.map (fun x -> x.State,x)
        |> Map.ofSeq
    
    let familyparse=
        FamilyCsv.GetSample().Rows
        |> Seq.map (fun row -> 
            { State = row.State |> State
              Pets = row.pets
              NumberofChildren = row.children
              NumberofMembers = row.familymem  })
    
    let familyMap =
        familyparse
        |> Seq.map (fun x -> x.State,x)
        |> Map.ofSeq
    
    let mapfunc =
        dataMap
        |> Seq.ofList
        |> Seq.map(fun (state,rows) ->
            { State = state
              Month = rows.Month
              Pets = familyMap.[state].Pets
              Children = familyMap.[state].NumberofChildren 
              GrossIncome = generalMap.TryFind(state).GrossIncome <-- Problem Line
              Family = familyMap.[state].NumberofMembers
            })
        |> List.ofSeq
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   FoggyFinder    8 年前

    你必须使用 Option.map :

    generalMap.TryFind(state) |> Option.map(fun s -> s.GrossIncome)