Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable in F#

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. 
like image 269
Søren Debois Avatar asked Apr 07 '14 19:04

Søren Debois


People also ask

What is Hashtable explain?

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.

Is there Hashtable in C?

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.

How do you write a hash function?

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.

Is Hashtable obsolete?

Hashtable. comparer has been deprecated. Use the KeyComparer properties instead.


2 Answers

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
like image 173
Daniel Avatar answered Oct 17 '22 10:10

Daniel


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 and None if not.

like image 22
MarcinJuraszek Avatar answered Oct 17 '22 08:10

MarcinJuraszek