开发者

Convert a sequence of dictionary keys to a set

The following code lists the set of keys found in a dictionary sequence (each dict is basically a row from a database). (I want to convert the keys to a set so I can compare 2 db tables)

for seqitem in tblseq do
    let keyset = seqitem.Keys |> Set.ofSeq    // works correctly
    printfn ">>> List: %A; Item Type: %A" keyset

Rather than print the keyset however I want to return it from a function but am having a problem with type inference. Tried the following but it does not work;

What I want to do is return these values as either an array of list (rather than print them)

let get_keyset tblseq = 
                tblseq |> Seq.iter (fun x ->  
                       x.Keys |> Set.ofSe开发者_运维知识库q                   
                     ) 

What am I missing here?


Using Seq.map as ildjarn suggests is one option (you may want to add Array.ofSeq to the end to get array of sets as you say in your qurestion).

An alternative approach is to use array comprehension:

let get_keyset (tblseq:seq<System.Collections.Generic.Dictionary<_, _>>) = 
    [| for x in tblseq -> x.Keys |> Set.ofSeq |]

The notation [| .. |] says that you want to create an array of elements and the expression following -> specifies what should be produced as an element. The syntax is essentially just a nicer way for writing Seq.map (although it supports more features).

You can also use this syntax for creating sets (instead of calling Set.ofSeq). In this case, it doesn't make much sense, because Set.ofSeq is faster and sorhter, but sometimes it is quite neat option. It allows you to avoid type annotations, because you can get key of a dictionary using KeyValue pattern:

let get_keyset tblseq = 
    [| for x in tblseq ->
         set [ for (KeyValue(k, v)) in x -> k ] |]


Use Seq.map rather than Seq.iter:

let get_keyset tblseq =
    tblseq
    |> Seq.map (fun (x:Dictionary<_,_>) -> x.Keys |> set)
    |> Array.ofSeq
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜