In C#, how do I make a static method called Sum
that takes one parameter of int
array type and returns the sum of its parameter's elements?
And what are ways to get the sum other than return Sum()
?
views:
132answers:
3You'd start by creating an int variable with a value of 0, say x
, iterating over the array and adding each of the values to x
, then returning x
.
Though you really need to start paying attention in class, cause this is basic stuff.
I think this classic article will help you at your first step of programming: http://www.catb.org/esr/faqs/smart-questions.html
Obviously, we won't do your homework for you, but here is a little hint: computing the sum of the elements of a collection is an instance of a more general pattern: reducing a sequence of things down to a single thing.
This idea of taking a sequence of things and reducing it down to a single thing has different names in different cultures. The most common name is "folding". It is also known as "reducing", "aggregating" or "accumulating". In mathematical category theory, it is known as a "catamorphism" (and no, I don't know what that means, either).
Pretty much every programming language provides a ready-made implementation of this concept. In the Smalltalk programming language, the method which implements this is called inject:into:
, in Ruby it is called inject
or reduce
, in PHP array_reduce
, in Haskell foldl
or foldr
(depending on whether it folds from left to right or right to left) or foldl1
, foldr1
(meaning that it uses the first element of the sequence instead of a user-supplied value as the starting value), in Scala foldLeft
, foldRight
or reduceLeft
, reduceRight
(depending on whether you supply the initial value or it simply uses the first element of the sequence), in C++ it is called std::accumulate
, ECMAScript calls it reduce
/ reduceRight
.
C# also has it, but I'm going to leave a little work for you.
There is a nice way to visualize what this "fold" does: you can simply think of it as replacing the commas in a sequence with a function of your choosing.
So,
fold + [1, 2, 3]
Basically means, take the sequence
1, 2, 3
and replace all commas with +
:
1 + 2 + 3
And that's how easy it is to compute the sum of an array.
Here are couple of examples in different programming languages to help you along.
Let's start with the simplest and IMHO most beautiful one: Haskell:
sum = foldl1 (+)
Yup, that's all there is to it. That's the complete implementation of a sum
function, which sums a list (Haskell prefers lists over arrays) of integers. It simply says "sum
ming a list is just fold
ing using the +
function".
Use it like so:
sum [1, 2, 3]
In Scala, it is almost as nice:
def sum(nums: Traversable[Int]) = nums reduceLeft { _ + _ }
Note that this function is actually much more general: it works for any Traversable
collection, not just for arrays.
Here's how to use it:
sum(Array(1, 2, 3))
Ruby:
def sum(nums)
nums.reduce(:+)
end
Again, this is much more general, since it works with any Enumerable
collection.
Use like this:
sum([1, 2, 3])
Here's ECMAScript:
function sum(nums) {
return nums.reduce(function (acc, el) { return acc + el; });
}
And the usage:
sum([1, 2, 3]);
C++:
int sum(vector<int> nums) {
return std::accumulate(nums.begin(), nums.end(), 0);
}
Note that I don't actually tell it what to use to fold the vector. That's because +
is the default. If you wanted to make it explicit, you'd use:
int sum(vector<int> nums) {
return std::accumulate(nums.begin(), nums.end(), 0, std::plus<int>);
}
Usage:
std::vector<int> v = { 1, 2, 3 };
sum(v);
Last but not least, here's C#:
static int Sum(int[] nums)
{
return nums.Sum();
}
Yep, that's right: there already is a Sum
method for arrays (or more precisely an extension method for IEnumerable
s).
Use it like so:
Sum(new int[] { 1, 2, 3 });
However, if you feel that this is cheating, then there is also an implementation of folding in C# (or more precisely the BCL). I won't tell you its name, but you will recognize it as soon as you see it.