Higher order functions in cSharp
Mar 22, 2013 00:00 · 371 words · 2 minute read
What are higher order functions?
Treating functions as regular objects enables us to use them as arguments and results of other functions. Functions that handle other functions are called higher order functions (codeProject).
Example
If you need to ask your method to call various methods in different situation you can use the Func delegate.
extension func
private static IEnumerable<int> Find(this IEnumerable<int> list, Func<int, bool> NumberMatchFormat) {
return list.Where(NumberMatchFormat).ToList();
}
The method is an extension of IEnumerable and accepts an integer as an input and returns a boolean. As an example, you can pass in the “IsEven” method as it accepts an integer and returns a Boolean:
method that accept integer and return bool
private static bool IsEven(int number) {
bool isEven = number % 2 == 0;
return isEven;
}
Calling
The method will be called by passing the method name as an input parameter from the higher function.
higher function
numbers.Find(IsEven);
Therefore, whenever the method is called it will invoke the “IsEven” method and will pass in the numbers that exist in the list one by one and return the matching list to the caller.
More functionality
You can add more functionality by adding different types of method to it .
prime number
private static bool IsPrime(int number) {
bool isPrime = true;
if (number == 1) {
isPrime = false;
} else {
for (var i = 2; i < number; i++) {
if (number % i == 0) {
isPrime = false;
}
}
}
return isPrime;
}
To check if it is a prime number you can call the above method from a higher function method as below.
calling isPrime
numbers.Find(IsPrime);
The next step could be writing the switch case and giving the choice to the end user to choose its desired function.
switch case for function
public static IEnumerable<int> FindNumberType(IEnumerable<int> numbers, TypeOfNumber TypeofNumber) {
switch (TypeofNumber) {
case TypeOfNumber.odd:
return numbers.Find(IsOdd);
case TypeOfNumber.even:
return numbers.Find(IsEven);
case TypeOfNumber.prime:
return numbers.Find(IsPrime);
case TypeOfNumber.perfect:
return numbers.Find(IsPerfect);
default:
throw new ArgumentOutOfRangeException("TypeofNumber");
}
}
Download
Feel free to download the full source code of this example that I did by pairing with Robert Cartlidge in TDD from my Github.
Special thanks to Kieran who helped me in proofreading of this post.