F#中的哈希表

Sør*_*ois 5 f# hashtable hashmap

是否有替代System.Collections.Generic.DictionarySystem.Collections.Hashtable

我对前者不满意,因为它使用返回值byref,即我需要做烦人的事情

let x = ref ""
if hashtable.TryGetValue (key, x) then
    // Found, value in !x
else
    // Not found. 
Run Code Online (Sandbox Code Playgroud)

我对后者不满意,因为它不是通用的.

编辑.我更喜欢在语法上看起来像通用的东西Map.tryFind,即

match Hashtable.tryFind k hashtable with
| None -> ...    // Not found
| Some v -> ...  // Found v. 
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 17

Out参数是.NET框架的一部分.但是,F#会通过自动将它们与返回值一起包装来最小化疼痛.所以,使用Dictionary<_,_>你可以做到:

match d.TryGetValue(key) with
| true, x -> ... //tuple of return value and out parameter
| _ -> ...
Run Code Online (Sandbox Code Playgroud)

请参阅MSDN上的" 按引用传递".

您可以轻松地将其包装到扩展中:

type System.Collections.Generic.Dictionary<'K, 'V> with
  member x.TryFind(key) =
    match x.TryGetValue(key) with
    | true, v -> Some v
    | _ -> None
Run Code Online (Sandbox Code Playgroud)


Mar*_*zek 5

你应该看看F#中有两种集合类型:

Collections.Set<'T> 班级(F#)

基于二叉树的不可变集合,其中比较是F#结构比较函数,可能使用关键值的IComparable接口的实现.

Collections.Map<'Key,'Value> 班级(F#)

不可变的地图.密钥按F#泛型比较排序.

Map 有你正在寻找的功能:

Map.TryFind

在地图中查找元素,Some如果元素位于地图的域中,则返回值,否则返回值None.

  • 但我不想要不可变和O(lg n)查找!我特意要求哈希表? (2认同)