C # function programming-inertia list tool-iterator

Source: Internet
Author: User

An effective task of processing data in today's programming languages and frameworks .. NET has a well-built collection class system, which uses the functions of the iterator to achieve sequential access to data. Inertia enumeration is an iterative method. Its core idea is to read data only when necessary. This idea ensures that any iterative algorithm is very effective and can flexibly read any amount of data as needed without causing excessive overhead. C # enumeration elements in functional programming. NET set type is based on an interface named IEnumberable. The following is the declaration of this interface: public interface IEnumerable {IEnumerator GetEnumerator ();} In fact, The IEnumberable interface only allows programmers to do one thing: another interface of the Query Class, IEnumerator: public interface IEnumerator {object Current {get;} bool MoveNext (); void Reset ();} the following class is actually the simplest implementation form of the iteration mode declared according to the IEnumberable and IEnumerator interfaces: public class EndlessListWithoutInterfaces {public EndlessListWithoutInterfaces GetEnumerator () {Return this;} public bool NoveNext () {return true;} public object Current {get {return "Something ";}}} the foreach structure of C # can also be used in the EndlessListWithoutInterfaces class: var list = new EndlessListWithoutInterfaces (); foreach (var item in list) {Console. writeLine (item);} this implementation is extremely basic, so this will lead to an infinite loop. The following is the implementation of the EndlessList class. This class uses IEnumerator and IEnumberable. These two classes are nested with each other, even though they do not need to be nested inside or outside. In fact, the nested IEnumerator class in the IEnumberable class is a common mode: public class EndlessList: IEnumerable {public class Enumerator: IEnumerator {int val =-1; public object Current {get {return val ;}} public bool NoveNext () {val ++; return true;} public void Reset () {val =-1 ;}} public IEnumerator GetEnumerator () {return new Enumerator () ;}} this implementation mode of the value sequence is very flexible and powerful. C # function programming-Implementation of the iterator Function C #2.0 introduces the iterator. It allows programmers to create the implementation of the IEnumerator/IEnumberable combination, without the need to manually implement any of the interfaces. In addition to non-generic interfaces, it also supports generic interfaces, so you can only implement IEnumerator. To apply this function, you only need to define a function that returns a certain type of value. The second criterion adopted by the compiler to use its conversion operations is to use at least one of several special keywords in the function. The most commonly used yield return statement. For example, the previous EndlessList example can be implemented by the following C # iterator: public static IEnumerable <int> EndlessListFunc () {int val = 0; while (true) yield return val ++;} the return type of this function is an IEnumberable <int>. Therefore, this function can be used in the original class instance that can implement this interface. The following statements can iteratively access the EndlessListFunc sequence: var list = EndlessListFunc (); foreach (var item in list) {Console. writeLine (item);} the entire declaration mode used by the IEnumerator/IEnumberable interfaces is related to inertia, that is, data is read only when necessary. The advantage of this pattern is that a sequence is only a small but flexible part of the entire algorithm, and there is no need to make any assumptions about its future use. The following code is an actual example of an iterator that reads data from a Web service using a search of a Twitter stream. Reading data from Web Services also adopts the inertia method because it uses the automatic paging technology. The iterator reads the new page as needed and returns the string sequence with unknown length to the caller. The caller processes the sequence as he prefers: private static void TwitterSearchIterator () {foreach (var tweet in GetTweets ("# msdn "). take (10) Console. writeLine (tweet);} private static IEnumerable <string> GetTweets (string searchString) {var url = "http://search.twitter.com/search.atom? Q = "; int page = 1; var escapedSearchString = searchString. replace ("@", "% 40 "). replace ("#", "% 23"); XNamespace ns = "http://www.w3.org/2005/Atom"; while (true) {var doc = XDocument. load (String. format ("{0} {1} & page = {2}", url, escapedSearchString, page); var entries = doc. root. elements (ns + "entry"); if (entries. count () = 0) yield break; foreach (var entry in entries) yield return entry. element (ns + "Author "). element (ns + "name "). value + ":" + WebUtility. htmlDecode (entry. element (ns + "title "). the Value; page ++ ;}} iterator not only returns the IEnumberable and IEnumberable <T> interfaces used in the preceding example, but also the IEnumerator and IEnumerator <T> interfaces. C # function programming-chained iterators can easily link function-form iterators and use them to create complex processing flows. This idea is widely used in LINQ, which is one of the most important concepts in functional programming. This section describes the EndlessListFunc iterator, which can return an infinite integer sequence. The iterator function that processes the sequence can be used with this iterator. For example, the following example is the implementation of the Take function. It accepts a certificate sequence and a Count value through parameters, and only returns the first few elements in the source sequence: public static IEnumerable <int> Take (int count, IEnumerable <int> source) {int used = 0; foreach (var item in source) if (count> used ++) yield return item; else yield break;} can use Take with EndlessListFunc: var FiveElements = Take (5, EndlessListFunc (); foreach (var item in FiveElements) Console. writeLine (item); this example shows how to use the iterator as a module. The second type of function used in the chain iterator is a function that uses the actual content, such as performing numerical calculations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.