public void AggregateExample() { // function fold (or reduce) // fold applies a function to each item in the list // it takes a list, and returns a single result (not a list) // It is an accumulative function // for example, SUM totals the 1st and 2nd item // then totals that result with the 3rd item and so on... // // LINQ (Aggregate, Sum, Average) // LINQ (Max, Min, Count) ImmutableList <int> setA = ImmutableList.Create(5, 4, 1, 3, 9, 8, 6, 7, 2, 12, 24); ImmutableList <int> setB = ImmutableList.Create(Enumerable.Range(1, 40).Where(x => x % 5 == 0).ToArray()); // predefined aggregates var total = setA.Sum(); var count = setB.Count(); var highestNumber = setB.Max(); // custom aggregate var multipleOf = setA.Aggregate((first, second) => first * second); // set the initial seed (accumulator value) var anotherMultiple = setA.Aggregate(100, (first, second) => first * second); }
public IConcurrentVersions <TVal, TVal> Update(TVal updated, VectorTime vectorTimestamp, long systemTimestamp = 0L, string creator = "") { var r = versions.Aggregate(Tuple.Create(ImmutableList <Versioned <TVal> > .Empty, false), (t, versioned) => { if (t.Item2) { return(Tuple.Create(t.Item1.Add(versioned), true)); } else { if (vectorTimestamp > versioned.VectorTimestamp) { // regular update return(Tuple.Create(t.Item1.Add(new Versioned <TVal>(updated, vectorTimestamp, systemTimestamp, creator)), true)); } else if (vectorTimestamp < versioned.VectorTimestamp) { // conflict already resolved return(Tuple.Create(t.Item1.Add(versioned), true)); } else { // confliciting update return(Tuple.Create(t.Item1.Add(versioned), false)); } } }); return(r.Item2 ? new ConcurrentVersionsList <TVal>(r.Item1, Owner) : new ConcurrentVersionsList <TVal>(r.Item1.Add(new Versioned <TVal>(updated, vectorTimestamp, systemTimestamp, creator)), Owner)); }
/// <summary> /// Enter the named barriers, one after the other, in the order given. Will /// throw an exception in case of timeouts or other errors. /// </summary> public void Enter(TimeSpan timeout, ImmutableList <string> names) { _system.Log.Debug("entering barriers {0}", names.Aggregate((a, b) => a = ", " + b)); var stop = Deadline.Now + timeout; foreach (var name in names) { var barrierTimeout = stop.TimeLeft; if (barrierTimeout.Ticks < 0) { _client.Tell(new ToServer <FailBarrier>(new FailBarrier(name))); throw new TimeoutException("Server timed out while waiting for barrier " + name); } try { var askTimeout = barrierTimeout + Settings.QueryTimeout; // Need to force barrier to wait here, so we can pass along a "fail barrier" message in the event // of a failed operation var result = _client.Ask(new ToServer <EnterBarrier>(new EnterBarrier(name, barrierTimeout)), askTimeout).Result; } catch (AggregateException) { _client.Tell(new ToServer <FailBarrier>(new FailBarrier(name))); throw new TimeoutException("Client timed out while waiting for barrier " + name); } catch (OperationCanceledException) { _system.Log.Debug("OperationCanceledException was thrown instead of AggregateException"); } _system.Log.Debug("passed barrier {0}", name); } }
public ISemantReturn <ImmutableList <Tuple <Option <String>, ExprType> > > GetMembers(Env env, ImmutableList <StructDecln> memberDeclns) { var result = memberDeclns.Aggregate(ImmutableList <Tuple <Option <String>, ExprType> > .Empty, (acc, decln) => acc.AddRange(Semant(decln.GetMemberDeclns, ref env)) ); return(SemantReturn.Create(env, result)); }
/// <summary> /// Enter the named barriers, one after the other, in the order given. Will /// throw an exception in case of timeouts or other errors. /// </summary> public void Enter(TimeSpan timeout, ImmutableList <string> names) { _system.Log.Debug("entering barriers " + names.Aggregate((a, b) => a = ", " + b)); var stop = Deadline.Now + timeout; foreach (var name in names) { var barrierTimeout = stop.TimeLeft; if (barrierTimeout.Ticks < 0) { _client.Tell(new ToServer <FailBarrier>(new FailBarrier(name))); throw new TimeoutException("Server timed out while waiting for barrier " + name); } try { var askTimeout = barrierTimeout + Settings.QueryTimeout; //TODO: Wait? _client.Ask(new ToServer <EnterBarrier>(new EnterBarrier(name, barrierTimeout)), askTimeout).Wait(); } catch (OperationCanceledException) { _client.Tell(new ToServer <FailBarrier>(new FailBarrier(name))); throw new TimeoutException("Client timed out while waiting for barrier " + name); } _system.Log.Debug("passed barrer {0}", name); } }
protected string GetSelectedFields(SqlSelectInfo info) { var selectFields = info.SelectFields(); var fields = selectFields.Count == 0 ? "*" : string.Join(", ", selectFields); fields = info.Distinct() ? $"DISTINCT {fields}" : fields; return(_selectFieldsModificators.Aggregate(fields, (result, callback) => callback(result))); }
public Product Of(Product product) { var result = names.Aggregate( Product.Empty, (sub, name) => sub.With(name, product.GetElement(name))); return(result); }
public VerifiedChanges VerifyWith(RoadNetworkView view) { var context = new VerificationContext(view, this); return(_changes.Aggregate( VerifiedChanges.Empty, (verifiedChanges, requestedChange) => verifiedChanges.Append(requestedChange.Verify(context)))); }
public void SendAllMessages(ImmutableList <Message> messages) { lock (this) { _queue = messages.Aggregate(_queue, (queue, message) => _queue.Enqueue(message)); } Perform(() => SendAndReceiveMessagesInternalAsync()); }
protected void AppendJoins(StringBuilder querySb, SqlSelectInfo info) { if (info.Joins().Count > 0) { var joins = _joinModificators.Aggregate(string.Join(SEPARATOR, info.Joins()), (result, callback) => callback(result)); querySb.Append(SEPARATOR).Append(joins); } }
public ImmutableList <Product> Execute(ImmutableList <FactReference> startReferences, FactGraph graph) { var start = starts.Single(); var initialTag = start.Name; var initialType = start.Type; var startingProducts = startReferences .Where(startReference => startReference.Type == initialType) .Select(startReference => Product.Empty.With(initialTag, new SimpleElement(startReference))) .ToImmutableList(); return(paths.Aggregate( startingProducts, (products, path) => path.Execute(products, graph) )); }
static void Main(string[] args) { ImmutableList <string> strings = ImmutableList <string> .Empty; strings.Add("Hello"); Console.WriteLine(strings.Count); // Still 0, original instance was not modified strings = strings.Add("Hello"); ImmutableList <string> allStrings = strings.Add(" ").Add("World"); Console.WriteLine("strings: [{0}] '{1}' ({2})", strings.Count, strings.Aggregate((agg, s) => agg + s), strings.GetHashCode()); // [1] 'Hello' Console.WriteLine("allStrings: [{0}] '{1}' ({2})", allStrings.Count, allStrings.Aggregate((agg, s) => agg + s), allStrings.GetHashCode()); // [3] 'Hello World' }
public RuleReference(Implication originalRule, IEnumerable<PropNetFlattener.Condition> conditions, IList<Term> productionTemplate = null) { OriginalRule = originalRule; ProductionTemplate = productionTemplate==null ? ImmutableList<Term>.Empty : productionTemplate.ToImmutableList(); Conditions = conditions.ToImmutableList(); int producttionTemplateHashCode = 1; if (productionTemplate != null) foreach (Term term in productionTemplate) producttionTemplateHashCode = 31 * producttionTemplateHashCode + (term == null ? 0 : term.GetHashCode()); int conditionsHashcode = Conditions.Aggregate(1, (current, cond) => 31 * current + (cond == null ? 0 : cond.GetHashCode())); _hashCode = producttionTemplateHashCode + conditionsHashcode; }
public static string NotesToString(ImmutableList <Note> Notes) => Notes.Aggregate("", (text, note) => text + NoteToChar(note));
public double Norm() { return(Math.Sqrt(Coordinates.Aggregate <double, double>(0, (accumulator, next) => accumulator + next * next))); }
public override int GetHashCode() => _problems.Aggregate(0, (current, error) => current ^ error.GetHashCode());
public Number Calculate(ImmutableList <INumberOrOperator> items) { var accumulation = items.Aggregate(ImmutableList.Create <INumberOrOperator>(), Accumulate); return(accumulation.Cast <Number>().Single()); }
protected string GetQueryString(StringBuilder querySb) => _wholeQueryModificators.Aggregate(querySb.ToString(), (result, callback) => callback(result));
public IQuantumState Transform(IQuantumState input) => transforms.Aggregate(input, (accum, next) => { return(next.Transform(accum)); });
public PgpWordAggregation Build() => new PgpWordAggregation( string.Join( _separator, _byteList.Aggregate(new List <string>(), AggregateByteToWordList)));
protected int GetCalculatedHashCode(ImmutableList <object> list) { return(list.Aggregate(13, (current, i) => current * 7 + i.GetHashCode())); }
public ISemantReturn<ImmutableList<Tuple<Option<String>, ExprType>>> GetMembers(Env env, ImmutableList<StructDecln> memberDeclns) { var result = memberDeclns.Aggregate(ImmutableList<Tuple<Option<String>, ExprType>>.Empty, (acc, decln) => acc.AddRange(Semant(decln.GetMemberDeclns, ref env)) ); return SemantReturn.Create(env, result); }
private ImmutableList <byte> ConcatSelected(ImmutableList <ISelector <byte> > sels) => sels.Aggregate(ImmutableList <byte> .Empty, (result, selector) => result.Concat(selector.GetSelected()).ToImmutableList() );
/// <summary> Sequence of the given create struct. </summary> /// <param name="cs"> The create struct. </param> /// <returns> A list of. </returns> public static Parser <ImmutableList <char> > SeqOf(ImmutableList <char> cs) { return(cs.Aggregate(Common.Return(ImmutableList <char> .Empty), (p, c) => p.Bind(r => Eq(c).Then(r.Add(c))))); }