Is there an alternative to System.Collections.Generic.Dictionary
or System.Collections.Hashtable
?
I'm unhappy with the former because it returns value using byref
, i.e., I need to do the annoying
let x = ref ""
if hashtable.TryGetValue (key, x) then
// Found, value in !x
else
// Not found.
I'm unhappy with the latter because it's not generic.
EDIT. I'd prefer something generic syntactically looking like Map.tryFind
, i.e.,
match Hashtable.tryFind k hashtable with
| None -> ... // Not found
| Some v -> ... // Found v.
A hash table, also known as a hash map, is a data structure that maps keys to values. It is one part of a technique called hashing, the other of which is a hash function. A hash function is an algorithm that produces an index of where a value can be found or stored in the hash table.
A Hash Table in C/C++ (Associative array) is a data structure that maps keys to values. This uses a hash function to compute indexes for a key. Based on the Hash Table index, we can store the value at the appropriate location.
With modular hashing, the hash function is simply h(k) = k mod m for some m (usually, the number of buckets). The value k is an integer hash code generated from the key. If m is a power of two (i.e., m=2p), then h(k) is just the p lowest-order bits of k.
Hashtable. comparer has been deprecated. Use the KeyComparer properties instead.
Out parameters are part of living with the .NET framework. F# does minimize the pain, however, by automatically tuplizing them along with the return value. So, using Dictionary<_,_>
you can do:
match d.TryGetValue(key) with
| true, x -> ... //tuple of return value and out parameter
| _ -> ...
See Passing by Reference on MSDN.
You could easily wrap that into an extension:
type System.Collections.Generic.Dictionary<'K, 'V> with
member x.TryFind(key) =
match x.TryGetValue(key) with
| true, v -> Some v
| _ -> None
There are two collection types in F# you should look at:
Collections.Set<'T>
Class (F#)Immutable sets based on binary trees, where comparison is the F# structural comparison function, potentially using implementations of the IComparable interface on key values.
Collections.Map<'Key,'Value>
Class (F#)Immutable maps. Keys are ordered by F# generic comparison.
Map
has a function you're looking for:
Map.TryFind
Lookup an element in the map, returning a
Some
value if the element is in the domain of the map andNone
if not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With