Skip to content

Instantly share code, notes, and snippets.

@BobStrogg
Last active July 17, 2017 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BobStrogg/f3a53c7c5a7b45b25d138c36589b0644 to your computer and use it in GitHub Desktop.
Save BobStrogg/f3a53c7c5a7b45b25d138c36589b0644 to your computer and use it in GitHub Desktop.
// 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