Dictionary &引用;“分包”;F语言的词典#

Dictionary &引用;“分包”;F语言的词典#,dictionary,f#,subset,Dictionary,F#,Subset,我是F#的初学者,我正在尝试编写一个函数来对给定列表的字典进行子集,并返回结果 我试过了,但没用 let Subset (dict:Dictionary<'T,'U>) (sub_list:list<'T>) = let z = dict.Clear sub_list |> List.filter (fun k -> dict.ContainsKey k) |> List.map (fun k -> (k,

我是F#的初学者,我正在尝试编写一个函数来对给定列表的字典进行子集,并返回结果

我试过了,但没用

let Subset (dict:Dictionary<'T,'U>) (sub_list:list<'T>) =
    let z = dict.Clear
    sub_list |> List.filter (fun k -> dict.ContainsKey k)
             |> List.map (fun k -> (k, dict.TryGetValue k) )
             |> List.iter (fun s -> z.Add s)

|> List.iter (fun s -> z.Add s);;
  --------------------------------------^^^

stdin(597,39): error FS0039: The field, constructor or member 'Add' is not defined
let Subset(dict:Dictionary)(sub_list:list您已编写:

let z = dict.Clear
z
属于
unit->unit
类型,但您正在调用
z.Add

我怀疑你想写信

let subset (dict:Dictionary<'T,'U>) (sub_list:list<'T>) =
    let z = Dictionary<'T,'U>() // create new empty dictionary
    sub_list |> List.filter (fun k -> dict.ContainsKey k)
             |> List.map (fun k -> (k, dict.[k]) )
             |> List.iter (fun s -> z.Add s)
    z

Edit(回答关于修改输入变量的编辑问题):


可以使用破坏性更新操作符
@fagui更新现有词典。没问题。我已经更新了我对第二个问题的回答。但是,如果我需要可变值,我应该使用词典而不是映射,对吗?在建议的映射解决方案中,你的函数会将词典作为参数吗?@FaguiCurtain在F中的
字典
的主要用途可能是与类一起使用,特别是当你在C/F混合环境中工作时。
映射
有一个
比较
要求,在F中使用的大多数类型都会自动给你这个要求,但类不会。总有一种方法可以表达你的程序逻辑,而不使用using可变状态。一旦你掌握了这一点,你应该更好地了解什么时候应用一点可变性是有利的。你可以在这里阅读更多关于
Map
s(和
Set
s)的内容:你能举一个或几个例子(或链接到)这样的逻辑。如何避免使用可变状态…@Fagui窗帘这个答案可以给你一个概述:这里有一个更深入的教程:如果你喜欢一本书,你可能想看看“现实世界的函数式编程”
let subset map subList =
    subList 
    |> List.choose (fun k -> Option.map (fun v -> k,v) (Map.tryFind k map))
    |> Map.ofList
let mutable dict = Dictionary<Key,Value>() // replace this with initial dictionary
let lst = [] // list to check against
dict <- sublist dict lst
let subset (d : System.Collections.Generic.Dictionary<'T,'U>) (sub_list : list<'T>) =
    sub_list 
    |> List.filter (d.ContainsKey >> not)
    |> List.iter (d.Remove >> ignore)