// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using System.Collections.Generic; namespace SortedSets { public partial class __default { public static Dafny.ISequence> SetToOrderedSequence(Dafny.ISet> set, Func less) { Dafny.ISequence[] itemArray = set.Elements.ToArray(); IComparer> lexicographicComapre = new LexicographicComparer(less); Array.Sort(itemArray, lexicographicComapre); return Dafny.Sequence>.FromElements(itemArray); } // This is to facilitate moving the above from a `method` to a `function method` in Dafny. public static Dafny.ISequence> SetToOrderedSequence2(Dafny.ISet> set, Func less) { return SetToOrderedSequence(set, less); } public static Dafny.ISequence SetToSequence(Dafny.ISet set) { return Dafny.Sequence.FromElements(set.Elements.ToArray()); } } // Lexicographically compares two dafny sequences according to a given // isLessThan function public class LexicographicComparer : Comparer> { private Func isLessThan; public LexicographicComparer(Func isLessThan) { this.isLessThan = isLessThan; } public override int Compare(Dafny.ISequence x, Dafny.ISequence y) { if (x == null || y == null) return Default.Compare(x, y); T[] xArr = x.Elements; T[] yArr = y.Elements; for (int i = 0; i < xArr.Length && i < yArr.Length; i++) { bool xLessThanAtIndex = isLessThan(xArr[i], yArr[i]); if (xLessThanAtIndex) { return -1; } bool yLessThanAtIndex = isLessThan(yArr[i], xArr[i]); if (yLessThanAtIndex) { return 1; } } // Reached the end of one array. Either they are equal, or the // one which is shorter should be considered "less than" return xArr.Length.CompareTo(yArr.Length); } } }