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 ?