Last active
July 17, 2017 20:36
-
-
Save BobStrogg/f3a53c7c5a7b45b25d138c36589b0644 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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