Difference between revisions of "FP Homework 3"

From Marek Běhálek Wiki
Jump to navigation Jump to search
Line 1: Line 1:
 
= Immutable data types =
 
= Immutable data types =
== Immutable Array ==
+
== 1 - Immutable Array ==
 +
 
 +
Study materials for immutable (persistent) arrays are at: https://en.wikipedia.org/wiki/Persistent_data_structure or https://en.wikipedia.org/wiki/Persistent_array
 +
 
 +
Let's have a class representing a ''triple'' or triplet, where the values can be set only once at the beginning, when we are creating an instance of this class.
 +
 
 +
An example can be following class implemented in C#:
  
 
<syntaxhighlight lang="csharp">
 
<syntaxhighlight lang="csharp">
private abstract class Triplet<A> : ITriplet
+
abstract class Triple<A>
        {
+
{
            private A[] data = new A[3];
+
  private readonly A[] data = new A[3];
            public Triplet(A left, A middle, A right)
+
  public Triple(A left, A middle, A right)
            {
+
  {
                data[0] = left;
+
    data[0] = left;
                data[1] = middle;
+
    data[1] = middle;
                data[2] = right;
+
    data[2] = right;
            }
+
  }
            public A this[int index]
+
  public A this[int index]
            {
+
  {
                get => index switch
+
    get => index switch
                {
+
    {
                    >= 0 and <= 2 => this.data[index],
+
      >= 0 and <= 2 => this.data[index],
                    _ => throw new IndexOutOfRangeException($"Index {index} out of range for a triplet.")
+
      _ => throw new IndexOutOfRangeException($"Index {index} out of range for a triplet.")
                };
+
    };
            }
+
  }
        }
+
}
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 10:18, 31 October 2022

Immutable data types

1 - Immutable Array

Study materials for immutable (persistent) arrays are at: https://en.wikipedia.org/wiki/Persistent_data_structure or https://en.wikipedia.org/wiki/Persistent_array

Let's have a class representing a triple or triplet, where the values can be set only once at the beginning, when we are creating an instance of this class.

An example can be following class implemented in C#:

abstract class Triple<A>
{
  private readonly A[] data = new A[3];
  public Triple(A left, A middle, A right)
  {
    data[0] = left;
    data[1] = middle;
    data[2] = right;
  }
  public A this[int index]
  {
    get => index switch
    {
      >= 0 and <= 2 => this.data[index],
      _ => throw new IndexOutOfRangeException($"Index {index} out of range for a triplet.")
    };
  }
}