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)
            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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: