Difference between revisions of "FP Homework 3"
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"> | ||
− | + | 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.") | |
− | + | }; | |
− | + | } | |
− | + | } | |
</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.")
};
}
}