Csharp Functional Programming

505

Example 1: Operator

public sealed class MySingleton
{
private static MySingleton _instance;

private MySingleton()
{
}

public static MySingleton Instance
{
get
{
if (_instance == null)
{
_instance = new MySingleton();
}

return _instance;
}
}

// Other stuff here
}
void Main()
{
MySingleton.Instance.ToString().Dump();
}

 

Example 2: Imutabliliy

public class DateRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }

public bool DateIsInRange(DateTime checkDate)
{
return Start.CompareTo(checkDate) <= 0 && End.CompareTo(checkDate) >= 0;
}
}

void Main()
{
var testDates =
new List<DateTime> {
DateTime.Parse(“2015-11-03”),
DateTime.Parse(“2015-11-01”),
DateTime.Parse(“2015-10-01”),
DateTime.Parse(“2015-12-01”)
};

var range = new DateRange { Start = DateTime.Parse(“2015-11-01”), End = DateTime.Parse(“2015-11-06″) };

testDates.ForEach(d => $”{d:yyyy-MM-dd} – {(range.DateIsInRange(d))}”.Dump());
}

 

Example 3: Disposable

void Main()
{
XDocument timeDoc;

using (var client = new System.Net.WebClient())
{
timeDoc = XDocument.Parse(client.DownloadString(“http://time.gov/actualtime.cgi”));
}

var ms = Convert.ToInt64(timeDoc.Root.Attribute(“time”).Value) / 1000;
var currentTime = new DateTime(1970, 1, 1).AddMilliseconds(ms).ToLocalTime();

currentTime.Dump();
}

 

Example 4: Lamdbda experession

 

Example 5: Interface

 

Example 6: Anonymous function

<Query Kind=”Program” />

public delegate decimal MathOperation(decimal left, decimal right);

public static decimal Add(decimal left, decimal right)
{
return left + right;
}

public static decimal Subtract(decimal left, decimal right)
{
return left – right;
}

public static decimal Multiply(decimal left, decimal right)
{
return left * right;
}

public static decimal Divide(decimal left, decimal right)
{
return left / right;
}

private static MathOperation GetOperation(char oper)
{
switch (oper)
{
case ‘+’: return Add;
case ‘-‘: return Subtract;
case ‘*’: return Multiply;
case ‘/’: return Divide;
}

throw new NotSupportedException(“The supplied operator is not supported”);
}

private static decimal Eval(string expr)
{
var elements = expr.Split(new[] { ‘ ‘ }, 3);
var l = Decimal.Parse(elements[0]);
var r = Decimal.Parse(elements[1]);
var op = elements[2][0];

return GetOperation(op)(l, r);
}

void Main()
{
Eval(“1 3 +”).Dump();
Eval(“10 5 -“).Dump();
Eval(“2 3 *”).Dump();
Eval(“14 2 /”).Dump();
}

 

Example 7: Pipeline data flow

 

 

NO COMMENTS