F#模式匹配泛型类型Map

问题描述 投票:0回答:1

这有效:

// sample objects    
let dctStrDbl = [("k1",1.0);  ("k2",2.0)]  |> Map.ofList
let dctStrStr = [("k1","v1"); ("k2","v2")] |> Map.ofList
let lstMisc   = [1; 2; 3]

let testStrDbl (odico : obj) : bool =
   match odico with
   | :? Map<string,double> as d -> true
   | _                          -> false

let testTrue  = testStrDbl (box dctStrDbl)    // this evaluates to true
let testFalse = testStrStr (box dctStrStr)    // this evaluates to false
let testMiscFalse = testStrDbl (box lstMisc)  // evaluates to false

但是我想在Map<'k,'v>类型的通用Map上进行模式匹配(而不是像Map<string,double>这样的特定类型Map)。在伪代码中:

let testGenMap (odico : obj) : bool =
    match odico  with
    | :? Map<'k,'v> as d -> true
    | _                  -> false

但它不起作用,因为这些都会评估为假

let testStrDblGen = testGenMap (box dctStrDbl)
let testStrDblGen = testGenMap (box dctStrStr)

我的问题:有没有办法匹配通用的Map<'k,'v>

=编辑=======

也许我应该给出一些额外的背景。我真正追求的是这样的事情

let findGen (odico : obj) (defVal : 'a) (apply : (Map<'k,'v> -> 'a)) : 'a = 
    match odico with
    | :? Map<'k,'v> as d -> apply d
    | _                  -> defVal // the object is not of the expected type

...我可以恢复通用类型'k'v。从这个意义上说,尼勒柯克提出的解决方案不会起作用。

f# pattern-matching
1个回答
2
投票

在通用Map上没有内置的模式匹配方法。

你可以做的是使用反射和活动模式:

let (|IsMap|_|) (x: obj) =
    if x.GetType().Name.StartsWith("FSharpMap") then Some () else None

let test = function
    | IsMap -> true
    | _ -> false

Map.empty<int,string> |> test // true
[1] |> test // false

=编辑=======

看到上面的编辑,可能以下内容将起作用:

let isMap<'k,'v when 'k : comparison> (m: obj) =
    typeof<Map<'k,'v>> = m.GetType()

let findGen odico defVal (apply : Map<'k,'v> -> 'a) =
    if odico |> isMap<'k,'v> then
        odico |> unbox<Map<'k,'v>> |> apply
    else
        defVal

let apply (x: Map<int,string>) = "the apply result"

findGen ([1,"one"] |> Map.ofList) "defVal" apply // "the apply result"
findGen (["one",1] |> Map.ofList) "defVal" apply // "defval"
findGen [1] "defVal" apply // "defval"
© www.soinside.com 2019 - 2024. All rights reserved.