Function programming in C,
In function programming, functions can be considered as data. A function can also be used as a parameter. A function can also return a function. For example, LINQ is based on functional programming.
Two examples lead to functional programming
Statement-based programming may be written like this:
String result; if (value> 0) {result = "positive";} else {result = "negative ";}
Function expressions can be simplified:
Var result = value> 0 "positive": "negative ";
Let's look at an example of filtering and sorting:
var i = 0;while(i < list.Count){ if(list[i] % 2 != 0) { list.RemoveAt(i); } else { ++i; }}list.Sort();
Function programming can be written as follows:
from x in list where x % 2 == 0 orderby x select x;
Or
list .where(x => x % 2 == 0) .OrderBy(x => x)
It can be seen that in LINQ, the returned results of an expression (function) can be used as the source of an expression (function) and can be chained.
Encapsulate a Functional Method
For example, read remote data.
void Main(){ XDocument timeDoc; using(var client = new System.Net.WebClient()) { timeDoc = XDocument.Parse(client.DonwloadString("")); } var ms = Convert.ToInt64(timeDoc.Root.Attribute("time").Value) / 1000; var currentTime = new DateTime(1977,1,1).AddMilliseconds(ms).ToLocalTime(); Console.WriteLine(currentTime);}
For the using part, we can extract a method.
private XDocument GetTime(){ using(var client = new System.Net.WebClient()) { return XDocument.Parse(client.DonwloadString("")); } }void Main(){ var timeDoc = GetTime(); var ms = Convert.ToInt64(timeDoc.Root.Attribute("time").Value) / 1000; var currentTime = new DateTime(1977,1,1).AddMilliseconds(ms).ToLocalTime(); Console.WriteLine(currentTime); }
However, it is not enough. The above GetTime method only encapsulates the using statement that implements the IDisposable interface of WebClient. Can I encapsulate all the using statements that implement the IDisposable interface?
public static class MyDisposable{ public static TResult Using<TDisposable, TResult>( Func<TDisposable> factory, Func<TDisposable, TResult> map) where TDisposable : IDisposable { using(var disposable = factory()) { return map(disposable); } }}void Main(){ var time = MyDisposable .Using( () => new System.Net.WebClient(), client => XDocument.Parse(client.DownloadString("")) ) .Root .Attribute("time") .Value; var ms = Convert.ToInt64(time) / 1000; var currentTime = new DateTime().AddMilliseconds(ms).ToLocalTime(); Console.WriteLine(currentTime);}
In function programming, the type returned by a function is basically the source instance of another function method.