Now, I haven’t applied myself to functional programming for, oh, nearly 20 years, when we didn’t get much further than writing factorials and fibs, so I’m really appealing to the community for some help in finding a solution.
My problem is this:
“Given a group of trade objects, I want to find all the combinations of trades that net to zero +/- some tolerance.”
My starter for ten is:
let NettedOutTrades trades tolerance = ...
Let’s assume my starting point is a previously constructed array of tuples (trade, value). What I want back is an array (or list, whatever) of arrays of trades that net out. Thus:
let result = NettedOutTrades [| (t1, -10); (t2, 6); (t3, 6); (t4; 5) |] 1
would result in:
[|
[| t1; t2; t4 |]
[| t1; t3; t4 |]
|]
I’m thinking that this could be achieved with a tail recursive construct, using two accumulators – one for the results and one for the sum of trade values. But how to put it all together…?
I’m sure I could knock out something procedural using c#, but it just doesn’t feel like the right tool for the job – I’m convinced there’s going to be an elegant, concise, efficient solution using the functional paradigm…I’m just not well practiced enough to identify it at present!
Since @Tomas already gave a direct solution, I thought I’d present a solution which highlights composition with higher-order functions as a powerful technique commonly used in functional programming; this problem can be decomposed into three discrete steps:
I lifted @Tomas’s underlying algorithm for calculating all (expect the empty) combinations
of a set but use a recursive sequence expression instead of a recursive function with an accumulator (I find this slightly easier to read and write).
I swapped the order of
tradesandtolerancein your proposed function signature, since it makes it easier to curry by tolerance and pipe in (trade,value) lists which is the typical style used in the F# community and generally encouraged by the F# library. e.g.: