-
Notifications
You must be signed in to change notification settings - Fork 0
Core Concepts
Ahmad Al-freihat edited this page Jan 1, 2026
·
1 revision
| Property | Description |
|---|---|
Head |
Gets the first element (same as First) |
First |
Gets the first element (same as Head) |
Last |
Gets the last element |
Tail |
Gets all elements except the first (returns null if only one element) |
Init |
Gets all elements except the last (returns null if only one element) |
Count |
Gets the number of elements |
The Head property always returns the first element safely, while Tail returns the remaining elements:
NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
int head = numbers.Head; // 1
NonEmptyList<int>? tail = numbers.Tail; // [2, 3, 4, 5]
// For a single-element list
NonEmptyList<int> single = new(42);
int singleHead = single.Head; // 42
NonEmptyList<int>? singleTail = single.Tail; // nullSimilarly, Init returns all elements except the last, and Last returns the final element:
NonEmptyList<int> numbers = new(1, 2, 3, 4, 5);
int last = numbers.Last; // 5
NonEmptyList<int>? init = numbers.Init; // [1, 2, 3, 4]The fundamental invariant of NonEmptyList<T> is that it always contains at least one element. This is enforced by:
- Constructor: Requires at least one element
-
Remove operations: Throw
InvalidOperationExceptionwhen attempting to remove the last element -
Clear(): Throws
NotSupportedException
// Construction requires at least one element
NonEmptyList<int> list = new(1); // OK
NonEmptyList<int> empty = new(); // Compile error!
// Cannot remove the last element
NonEmptyList<int> single = new(1);
single.Remove(1); // Throws InvalidOperationException
// Cannot clear
list.Clear(); // Throws NotSupportedException- Learn different ways of Creating NonEmptyList
- Explore Functional Operations like Map and Reduce