按索引获取记录项的元素 (F#)

Get element of a record item by index (F#)

我有一条记录,比如下面的结构

 type RelativeSpeedModifier =
    { ContactSpeed: Range<Speed>
      OneThird: int
      TwoThirds: int
      Standard: int        
     }

什么是 easy/elegent 通过索引获取元素的方式(例如,非硬编码 if 语句)

例如伪代码

let x = { ContactSpeed: 12, OneThird: 22, ...}
let speedModifier = x.[1]
//speedModifier = 22

解构如何

let x = { ContactSpeed: 12, OneThird: 22, ...}
let { ContactSpeed=speedModifier; } = x 

我认为您无法通过索引获得记录的 属性。

你可以通过反思来做到这一点,虽然我真的不推荐它:

open Microsoft.FSharp.Reflection

let getField i rcd =
    let info = FSharpType.GetRecordFields(rcd.GetType()).[i]
    FSharpValue.GetRecordField(rcd, info)

let x = { ContactSpeed: 12, OneThird: 22, ...}
let speedModifier = getField 0 x

您可以添加 indexer 以输入:

 type RelativeSpeedModifier =
    { ContactSpeed: Range<Speed>
      OneThird: int
      TwoThirds: int
      Standard: int        
     }
    with member r.Item (index:int) =
          match index with
          | 1 -> r.OneThird
          ...
          | _ -> failwith "out of range"