Wednesday, August 24, 2011

Getting Started with the F# PowerPack - Part 3

In this series, I'm walking you through various features provided by the F# PowerPack.

Here are the links to the previous posts:

- Part 1
- Part 2

In this post, I'll discuss HashMultiMap and LazyList.

HashMultiMap: provides a nice description of the HashMultiMap type. Here's an excerpt from that link "HashSet and HashMultiMap are mutable structures, and both are implemented using hash comparison. When inserting a value, structural hash (or a user-supplied hash function) and (=) are used to find if a key already exists. Therefore, these are a good choice when the key is a complex or recursive data structure. HashSet contains keys only, and HashMultiMap contains keys and an associated value. Each key can only appear once in a HashSet or HashMultiMap, but multiple values can be bound to a single key in a HashMultiMap." Note: HashSet is now in System.Core. The version in the F# PowerPack has been deprecated.

Here is an example of HashMultiMap:
let hashSeq = 
    seq { for i in 1..100 do 
            yield ("key" + i.ToString()), ("value" + i.ToString())}
let hashMultiMap = HashMultiMap<string, string>(hashSeq, HashIdentity.Structural)
printfn "The value from the HashMultiMap for key:key5 is %s" (hashMultiMap.Item "key5")

Matthew Podwysocki has a nice post on Lazy Evaluation in F# that includes a section on LazyList. Here are a few excerpts from this post that explain the LazyList type. "The LazyList is a list which caches the results of the computed results on the items inside the collection." "The values aren't computed until the first is accessed, and then the results are cached."

The following contrived example shows the LazyList in use:
seq { for i in 1..10 do yield ("value" + i.ToString())}
|> LazyList.ofSeq
|> LazyList.iter(fun v -> printfn "The value from the LazyList is %s" v)
Wrapping Up:

That's it for today. You can find these examples (and several others) on my GitHub:

No comments:

Post a Comment