2

I am trying to create an immutable collection type that behaves as a hybrid of multiset/bag and Map that records the number of occurrences of each item.

I can write a mutable one with code a little like below and I tried to write an immutable one by inheriting from Map but Map is sealed and will not let me define any overrides.

type TallySet<'k_t when 'k_t : comparison>() = class
    //    inherit Map<'k_t, int>
    let m_map:((Map<'k_t, int>) ref) = ref (Map.empty)

    member x.add item =
        m_map :=
            match (!m_map).TryFind item with
                | None -> (!m_map).Add(item, 1)
                | Some n -> (!m_map).Add(item, 1 + n)
       !m_map

    member x.Count with get() = Map.fold (fun cc k v -> cc + v) 0 !m_map
end

What should I write ?

  • Looking at the code for the [Map type in F#](https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/map.fs) and the [corresponding signature file](https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/map.fsi) would be a good start. Note that most of the functions you'd use use day to day are in the map module, (scroll slightly down). – asibahi Sep 28 '16 at 11:52

1 Answers1

2

Have a look at ExtCore.Collections.Multiset. As in your code, it's just a map with the value type set to the count. Multiset.add and Multiset.count correspond to the members in your example.