Function with uncertain return type

  • Thread starter Thread starter RP
  • Start date Start date
R

RP

I have a function to return minimum of n numbers. Code given below:

=====[ CODE ]===============================
private int FindMinimum(int[] numbers)
{
int temp, i;
temp = 0;
for (i=0; i<= numbers.length; i++)
{
temp = Math.Min(temp, numbers);
}
return temp;
}
==========================================

I have not checked the above code. I actually want that the return
type be generic, so that I can use this function for int, double or
decimal. How to modify the above function to use generic return type?
 
RP said:
I have a function to return minimum of n numbers. Code given below:

=====[ CODE ]===============================
private int FindMinimum(int[] numbers)
{
int temp, i;
temp = 0;
for (i=0; i<= numbers.length; i++)
{
temp = Math.Min(temp, numbers);
}
return temp;
}
==========================================

I have not checked the above code. I actually want that the return
type be generic, so that I can use this function for int, double or
decimal. How to modify the above function to use generic return type?


private static T FindMinimum<T>(IEnumerable<T> collection, T
identityElement) where T : IComparable<T> {
T min = identityElement;
foreach (T t in collection) {
if (t.CompareTo(min) < 0) min = t;
}
return min;
}

Sample use:

FindMinimum(new int[] { 2, 3, 1 }, Int.MaxValue) == 1
FindMinimum(new int[] { }, Int.MaxValue) == Int.MaxValue

You can leave out the "identity element" thing and restrict the function to
operate on non-empty collections only, but that's not as concise:

private static T FindMinimum<T>(IEnumerable<T> collection) where T :
IComparable<T> {
IEnumerator<T> enumerator = collection.GetEnumerator();
if (!enumerator.MoveNext()) throw new ArgumentException("Attempt to
find the minimum of an empty collection.");
T min = enumerator.Current;
while (enumerator.MoveNext()) {
if (enumerator.Current.CompareTo(min) < 0) min = enumerator.Current;
}
return min;
}
 
It is worth mentioning that .NET 3.5 provides this functionality "out
of the box" via Enumerable.Min<T>() etc. Also, Comparer<T>.Default can
be used if you don't want to enforce the constraint in the API; while
constraints are a good thing, the downside is that it tends to
snowball, so higher up functions end up with 3 or 4 constraints that
are only used in edge-cases. This approach [Comparer<T>.Default, no
constraint] is what LINQ uses (.NET 3.5).

Marc
 
Back
Top