Grow-Only Set In C# « Onor.io
source link: https://onor.io/2018/06/21/grow-only-set-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Grow-Only Set In C#
So I’ve been trying to keep my development skills somewhat sharp by working on coding up certain data structures in C#. Course I’d rather do this with F# or even some more interesting FP language (Elm anyone?) but I do have a need to be able to show this code to student developers and the students I get know C#.
So there are a few things:
1.) I found it hard to find an abstract discussion of these CRDT data structures. This article on Wikipedia is fine but there’s some math notation there that I find a bit tough to read. I suppose I need to do a bit more digging.
2.) It’s a bit of an impedance mismatch to try to build a read-only data structure in an imperative language. OO especially doesn’t really seem to fit the idea of returning new data (as opposed to mutating in place) as well as it might. Still we soldier on as best we can.
Without any further ado here’s my code.
using
System.Collections.Generic;
using
System;
using
System.Linq;
namespace
CRDT
{
public
class
GrowOnlySet<T>
{
private
readonly
HashSet<T> payload;
public
GrowOnlySet()
{
payload =
new
HashSet<T>();
}
public
GrowOnlySet(HashSet<T> newstore)
{
payload = newstore ??
throw
new
ArgumentNullException(nameof(newstore));
}
public
HashSet<T> GetPayload() =>
new
HashSet<T>(payload);
public
GrowOnlySet<T> Add(T element)
{
payload.Add(element);
return
new
GrowOnlySet<T>(GetPayload());
}
public
bool
Lookup(T element) => payload.Contains(element);
public
bool
Compare(GrowOnlySet<T> other) => (other ==
null
) ?
false
: other.GetPayload().IsSubsetOf(payload);
public
GrowOnlySet<T> Merge(GrowOnlySet<T> other)
{
if
(other ==
null
)
throw
new
ArgumentNullException(nameof(other));
return
new
GrowOnlySet<T>(
new
HashSet<T>(payload.Union(other.GetPayload())));
}
}
}
I would greatly appreciate any comments that folks with a deeper knowledge of CRDT data structures may care to share.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK