📋 Match Arrays Like Prolog
Match first element, last element, empty list — all with pattern matching. List patterns make array processing declarative.
📝 Basic Patterns
int[] numbers = [1, 2, 3, 4, 5];
// Match first two elements
if (numbers is [1, 2, ..]) {
Console.WriteLine("Starts with 1,2");
}
// Match last two elements
if (numbers is [.., 4, 5]) {
Console.WriteLine("Ends with 4,5");
}
// Extract middle elements
if (numbers is [1, .. var middle, 5]) {
Console.WriteLine($"Middle: {string.Join("", "", middle)}"); // 2,3,4
}
// Empty check
if (numbers is []) {
Console.WriteLine("Empty array");
}
🎯 Switch with List Patterns
string GetCommandType(string[] args) => args switch
{
[] => "No arguments",
["help"] => "Help command",
["build"] => "Build command",
["test", ..] => "Test command with arguments",
["run", var project, ..] => $"Run project: {project}",
["-v" or "--version"] => "Version command",
[_, _] => "Exactly two arguments",
[_, .., _] => "At least two arguments",
_ => "Unknown command"
};
// Nested list patterns
int[][] matrix = [[1, 2], [3, 4], [5, 6]];
if (matrix is [[1, 2], ..]) {
Console.WriteLine("First row is 1,2");
}
✅ Real-World Example
public static string ParseLogLevel(string[] parts) => parts switch
{
// ERROR: Database connection failed
["ERROR", "Database", ..] => "Database error",
// WARNING: Low disk space on /dev/sda
["WARNING", "Disk", .. var details] => $"Disk warning: {string.Join(" ", details)}",
// INFO: User 123 logged in
["INFO", "User", var userId, "logged in"] => $"User {userId} login",
// Any error with timestamp [2024-01-15 ERROR]
[var timestamp, "ERROR", ..] when timestamp.StartsWith("[") => $"Error at {timestamp}",
// Default
_ => "Unknown log entry"
};
// Usage in parser
string[] logParts = ["ERROR", "Database", "connection", "timeout"];
string result = ParseLogLevel(logParts); // "Database error"
💡 Benefits
- No more index out of bounds checks (pattern handles length)
- Declarative parsing of command-line arguments
- Destructuring with .. var captures rest of array
- Works with any type that has length/indexer
“Replaced 30 lines of CLI argument parsing with 10 lines of list patterns. No more manual bounds checks. List patterns make array handling elegant and safe.”
