namespace FSharp.Collections.Immutable.Tests open System.Collections.Immutable open Microsoft.VisualStudio.TestTools.UnitTesting open FSharp.Collections.Immutable [] type EquatableArrayPatternTests () = /// Names the pattern that an array of up to five elements matches first. static let describe (array : EquatableArray) = match array with | Arr0 -> "none" | Arr1 single -> $"one {single}" | Arr2 (first, second) -> $"two {first} {second}" | Arr3 (first, second, third) -> $"three {first} {second} {third}" | ArrN 4 -> $"four {array[3]}" | _ -> "more" /// The elements of arrays of none to five elements, with the text that `describe` gives for each. static member Lengths = seq { struct ([||], "none") struct ([| 1 |], "one 1") struct ([| 1; 2 |], "two 1 2") struct ([| 1; 2; 3 |], "three 1 2 3") struct ([| 1; 2; 3; 4 |], "four 4") struct ([| 1; 2; 3; 4; 5 |], "more") } [] member _.``each length matches its pattern and longer arrays fall through`` (elements : int array, expected : string) = Assert.AreEqual (expected, describe (ea elements), "the array must match the pattern of its length, or fall through") [] member _.``the default value matches Arr0`` () = Assert.AreEqual ("none", describe Unchecked.defaultof>, "the default value must match Arr0") [] member _.``a struct tuple payload also binds with the struct keyword`` () = let sum = match ea [| 1; 2 |] with | Arr2 (struct (first, second)) -> first + second | _ -> 0 Assert.AreEqual (3, sum, "Arr2 must bind the struct tuple with the struct keyword too") [] member _.``a pattern nested in a union case matches the children`` () = let sum = match Branch (ea [| Leaf 1; Leaf 2 |]) with | Branch (Arr2 (Leaf first, Leaf second)) -> first + second | _ -> 0 Assert.AreEqual (3, sum, "Arr2 must match the children of a union case and their own patterns") [] member _.``an ImmutableArray matches after a wrap without a copy`` () = let items = ImmutableArray.Create (7, 8) let matched = match EquatableArray items with | Arr2 (first, second) -> first * 10 + second | _ -> 0 Assert.AreEqual (78, matched, "a wrapped ImmutableArray must match the patterns")