FP Homework 3

From Marek Běhálek Wiki
Revision as of 10:18, 31 October 2022 by Beh01 (talk | contribs)
Jump to navigation Jump to search

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.")
    };
  }
}