Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// LINQPad script showing a "use" for out parameters on iterators.
// It's a mockup of a discrete event simulator process (similar to SimPy - http://simpy.readthedocs.io).
// Since it's not possible to use 'out' with iterators, this uses an Action<T> instead.
// I'm not suggesting it's valid or in good taste :)
void Main()
{
foreach (var ie in Simulate().Take(100)) ie.Dump();
}
Container someContainer = new Container();
Container anotherContainer = new Container();
IEnumerable<IEvent> Simulate()
{
while (true)
{
yield return someContainer.Get(1);
yield return new WaitEvent(0.2);
int quantity = 0;
foreach (var ie in GetSomeNestedEvents(q => quantity = q)) yield return ie;
yield return anotherContainer.Put(quantity);
}
}
IEnumerable<IEvent> GetSomeNestedEvents(Action<int> setQuantity)
{
setQuantity(0);
yield return new WaitEvent(0.1);
setQuantity(42);
}
interface IEvent
{
}
class Event : IEvent
{
}
class WaitEvent : Event
{
public double Duration { get; }
public WaitEvent(double duration) => Duration = duration;
}
class GetEvent : Event
{
public int Quantity { get; }
public GetEvent(int quantity) => Quantity = quantity;
}
class PutEvent : Event
{
public int Quantity { get; }
public PutEvent(int quantity) => Quantity = quantity;
}
class Container
{
public GetEvent Get(int quantity) => new GetEvent(quantity);
public PutEvent Put(int quantity) => new PutEvent(quantity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment