MapWhile.cs (3307B)
1 using Std.Convert; 2 using Std.Maybe; 3 using Std.Ops; 4 using Std.Result; 5 using System; 6 using System.Runtime.InteropServices; 7 #region Namespaces 8 namespace Std.Iter { 9 #region Types 10 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 0)] 11 public struct MapWhile<T, TIter, T2>: IInto<MapWhile<T, TIter, T2>>, IIterator<T2> where T: notnull where TIter: notnull, IIterator<T> where T2: notnull { 12 13 #region Type-level Constructors 14 #endregion 15 16 #region Instance Constructors 17 public MapWhile() => throw new InvalidOperationException("Parameterless constructor is not allowed to be called!"); 18 internal MapWhile(TIter iter, Fn<T, Maybe<T2>> f) => (_iter, _f) = (iter, f); 19 #endregion 20 21 #region Type-level Fields 22 #endregion 23 24 #region Instance Fields 25 readonly Fn<T, Maybe<T2>> _f; 26 [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Can't be readonly since we call mutable methods on it.")] 27 TIter _iter; 28 #endregion 29 30 #region Type-level Properties 31 #endregion 32 33 #region Instance Properties 34 #endregion 35 36 #region Type-level Functions 37 #endregion 38 39 #region Instance Functions 40 public Result<Unit, ulong> AdvanceBy(ulong n) => IIterator<T2>.AdvanceByDefault(ref this, n); 41 public ulong Count() => IIterator<T2>.CountDefault(ref this); 42 public override readonly bool Equals(object? _) => false; 43 public TInit Fold<TInit>(TInit init, Fn<TInit, T2, TInit> f) where TInit: notnull { 44 45 static Fn<TInit, T2, Result<TInit, Bottom>> fn(Fn<TInit, T2, TInit> g) => (acc, x) => new(g(acc, x)); 46 return TryFold(init, fn(f))._ok; 47 } 48 public override readonly int GetHashCode() => 0; 49 public readonly MapWhile<T, TIter, T2> Into() => this; 50 public Maybe<T2> Last() => IIterator<T2>.LastDefault(ref this); 51 public Maybe<T2> Next() { 52 53 var x = _iter.Next(); 54 return x.IsNone ? Maybe<T2>.None() : _f(x._some); 55 } 56 public Prod<ulong, Maybe<ulong>> SizeHint() => new(ulong.MinValue, _iter.SizeHint().Item1); 57 public override readonly string ToString() => string.Empty; 58 public Result<TInit, TErr> TryFold<TInit, TErr>(TInit init, Fn<TInit, T2, Result<TInit, TErr>> f) where TInit: notnull where TErr: notnull { 59 60 static Fn<TInit, T, Result<TInit, Result<TInit, TErr>>> fn(Fn<TInit, T2, Result<TInit, TErr>> g, Fn<T, Maybe<T2>> pred) => (acc, x) => { 61 62 var mbe = pred(x); 63 64 if (mbe.IsSome) { 65 var res = g(acc, mbe._some); 66 return res.IsErr ? new(res) : new(res._ok); 67 } else { 68 return new(new Result<TInit, TErr>(acc)); 69 } 70 }; 71 var r = _iter.TryFold(init, fn(f, _f)); 72 return r.IsErr ? r._err : new(r._ok); 73 } 74 readonly Result<MapWhile<T, TIter, T2>, Bottom> ITryInto<MapWhile<T, TIter, T2>, Bottom>.TryInto() => new(this); 75 #endregion 76 77 #region Operators 78 #endregion 79 80 #region Types 81 #endregion 82 } 83 #endregion 84 85 #region Namespaces 86 #endregion 87 } 88 #endregion