Given a list of objects i need to return a list consisting of the objects and the sum of a property of the objects for all objects in the list seen so far.
More generally given
var input = new int[] {1,2,3}
I would like to have the output of
// does not compile but did not want to include extra classes. var output = { (1,1), (2,3), (3,6) };
What is the ‘right’ functional way to do this? I can do it in a standard iterative approach of course but I am looking for how this would be done in a functional, lazy way.
Thanks
in functional terms this is a combination of :
zip
take two sequences and create a sequence of tuples of the elements
and
map
Take a function
fand a sequence and return a new sequence which is f(x) for each x in the original sequenceThe zip is trivial in c# 4.0 Taking the simplistic implementation from there we have
We then need the map. We already have it, it’s what we call Select in c#
But it is safer to bake this into it’s own method (no currying in c#) and allow support for arbitrary types/accumulations.
Then we can put them together like so
This will iterate over the sequence twice, but is more general. You could choose to do the accumulator yourself within a standard select and a simple closure but it is no longer so useful as a ‘building block’ which is one of the driving forces behind functional programming.
Tuple support is a pain except within a method as the anonymous types don’t traverse method boundaries without quite a bit of hassle. A few basic tuples should be included in c# 4.0. assuming a tuple class/struct called
Pair<T,U>you could do:Where c# linq becomes much more cumbersome than languages like f# is the poor support for operators, currying and tuples unless you keep everything inside one function and ‘reconstruct it’ each and every time for each type.