F# 中的动态查找

Dynamic Lookup in F#

谁能帮我看看 Tomas Petricek 的文章:http://tomasp.net/blog/fsharp-dynamic-lookup.aspx/#dynfslinks? 问题是它已经严重过时了。我知道命名空间

open Microsoft.FSharp.Quotations.Typed
open Microsoft.FSharp.Quotations.Raw

都走了。所以我去掉了开口。但是仍然有错误。 "Typed" 未定义。 "RecdGet" 未定义。我怀疑他们不是最后一个。我正试图向我的老板证明 F# 非常适合用于数据库规范化。字段的动态查找确实可以帮助我处理具有不同前缀的相似命名字段。

fpish 上还有 Tomas 的 post:https://fpish.net/topic/None/57493,据我所知早于这篇文章

这是一个粗略的等价物:

open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns

type DynamicMember<'t,'u> = Expr<'t -> 'u>

let getValueReader (expr:DynamicMember<'recdT, 'fieldT>) = 
  // Match the quotation representing the symbol
  match expr with
  | Lambda(v, PropertyGet (Some (Var v'), pi, [])) when v = v' ->
      // It represents reading of the F# record field..
      // .. get a function that reads the record field using F# reflection
      let rdr = Reflection.FSharpValue.PreComputeRecordFieldReader pi

      // we're not adding any additional processing, so we just
      // simply add type conversion to the correct types & return it
      ((box >> rdr >> unbox) : 'recdT -> 'fieldT)
  | _ -> 
      // Quotation doesn't represent symbol - this is an error
      failwith "Invalid expression - not reading record field!"

type SampleRec = { Str : string; Num : int }

let readStrField = getValueReader <@ fun (r : SampleRec) -> r.Str @>
let readNumField = getValueReader <@ fun (r : SampleRec) -> r.Num @>   

let rc = { Str = "Hello world!"; Num = 42 }
let s, n = readStrField rc, readNumField rc

printfn "Extracted: %s, %d" s n