F#中的动态查找

时间:2017-02-17 13:28:56

标签: f# quotations

有人可以用Tomas Petricek的文章帮助我:http://tomasp.net/blog/fsharp-dynamic-lookup.aspx/#dynfslinks? 问题是它严重过时了。我理解名称空间

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

走了。所以我删除了开口。但仍有错误。 "类型化"没有定义。 " RecdGet"没有定义。我怀疑他们不是最后一个。我试图向我的老板证明F#可以用于数据库规范化。动态查找字段确实有助于我处理具有不同前缀的类似命名字段。

还有关于fpish的帖子:https://fpish.net/topic/None/57493,我在文章之前就已经理解了

1 个答案:

答案 0 :(得分:3)

这是一个粗略的等价物:

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
相关问题