// new features in C# 3.0/4.0
using System;
// New in C# 3.0: Typed Lambda Terms.
// the syntax of lambda x.E in C# is (x => E)
// Func is a generic delegate that can be used for the type of lambda
// terms. Other delegates can also be used (see "fun" below).
class purelambdas /// A,B,C will represent generic types
{
static Func I = (x=>x); // lambda x.x
static Func> K = (x=>(y=>x)); // lambda x.lambda y.x
// unfortunately, this notation makes S too much of a mess.
}
public class newstuff
{
static int reduce(int[] A, int id, Func f)
{
int ax = id; // start with identity
foreach(int x in A) ax = f(ax,x);
return ax;
}
// closure lambda term
static Func maketoggle()
{
bool val = false; // environment variable.
return ()=>{ val = !val; return val; }; // "statement lambda" needs {}
}
// compatibility of lambda terms with delegates
public delegate int fun(int x); // equivalent to Func
public static void Main()
{
Func odd; // type of f is int->bool
odd = (x => x%2==1); // lambda x. x is odd
Console.WriteLine(odd(3)); // prints true
int[] A = {1,7,5,3};
Console.WriteLine(reduce(A, 0, (x,y)=>x+y)); // prints 16
Func t1 = maketoggle();
Func t2 = maketoggle();
t1(); t1(); t2();
Console.WriteLine(t1()+ " "+ t2()); // prints True False
fun morefun = null; // fun is the delegate type defined above
morefun = (n)=>{if (n<2) return 1; else return n*morefun(n-1);};
Console.WriteLine(morefun(6)); // prints 6!
//////////// new in C# 4.0 (C# 2010): "dynamic language runtime"
// Not all language developments are steps in the right direction:
dynamic a = 3.14;
dynamic b = "abc";
Console.WriteLine(a*b); // this sucker will compile!
}//main
}//newstuff