Jump to content

Higher-order functions: Difference between revisions

Added C# 1+, 2+, 3+ examples.
(added Go)
(Added C# 1+, 2+, 3+ examples.)
Line 2:
 
C.f. [[First-class functions]]
 
=={{header|ActionScript}}==
<lang actionscript>package {
Line 267 ⟶ 268:
std::cout << first(second(), 2) << std::endl;
return 0;
}</lang>
 
=={{header|C sharp|C#}}==
 
Each example below does the same thing and has the same output:
<pre>
f=Add, f(6, 2) = 8
f=Mul, f(6, 2) = 12
f=Div, f(6, 2) = 3
</pre>
 
===Delegates: Named methods===
This works for all standard versions of C#.
 
<lang csharp>using System;
delegate int Func2(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static int Mul(int a, int b)
{
return a * b;
}
static int Div(int a, int b)
{
return a / b;
}
static int Call(Func2 f, int a, int b)
{
return f(a, b);
}
 
static void Main()
{
int a = 6;
int b = 2;
Func2 add = new Func2(Add);
Func2 mul = new Func2(Mul);
Func2 div = new Func2(Div);
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(add, a, b));
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(mul, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b));
}
}</lang>
 
===Delegates: Anonymous functions===
Anonymous functions added closures to C#.
 
{{works with|C sharp|C#|2+}}
 
<lang csharp>using System;
delegate int Func2(int a, int b);
class Program
{
static int Call(Func2 f, int a, int b)
{
return f(a, b);
}
 
static void Main()
{
int a = 6;
int b = 2;
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x + y; }, a, b));
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x * y; }, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x / y; }, a, b));
}
}</lang>
 
===Lambdas===
Lambda functions are syntactic sugar for anonymous functions. The <code>System</code> namespace also gained some common delegates, such as <code>Func<T0, T1, T2></code>, which refers to a function that returns a value of type <code>T0</code> and has two parameters of types <code>T1</code> and <code>T2</code>.
 
{{works with|C sharp|C#|3+}}
 
<lang csharp>using System;
class Program
{
static int Call(Func<int, int, int> f, int a, int b)
{
return f(a, b);
}
 
static void Main()
{
int a = 6;
int b = 2;
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call((x, y) => x + y, a, b));
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call((x, y) => x * y, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call((x, y) => x / y, a, b));
}
}</lang>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.