Carl Nolan’s ramblings on development
In a previous post I talked about a mechanism for Parallel Process Execution with Conditional Completion. This code was a direct translation from a C# pattern. However it is worth noting that the Command pattern is not actually necessary in functional languages.
To demonstrate this here is a version of the ForEachPartial method, from the previous post, that operates on a sequence of functions; rather than a sequence of command types:
As you can see the ForEachPartial method now executes, in parallel using PSeq, the specified functions. This is enabled as F# supports higher order functions, removing the need to wrap the command and parameters into a Command type. A word of not about PSeq. PSeq is based on PLINQ, and as a result a loop state is unavailable. This means a cancellation token is used to terminate future scheduled iterations.
The collectorState function takes the result of the operation execution and passes it into the collector function, performing the necessary locking. The return from the collector operation determines if further iterations are cancelled. The operation function merely wraps the call to the long running process.
If one wanted to support C# clients one could still support an override that operates using the Command pattern.
This override merely converts the sequence of Command types into functions of the signature (unit –> ‘a). The definition of the command types is:
To provide a more functional interface, one can also provide an extension to PSeq that operations on the sequence of functions:
This way one gets the best of both worlds, a functional call syntax for when programming in F# and an .Net signature that allows one to easily use the code from C#.