F # getting started with functional programming in. NET Framework

Source: Internet
Author: User
Tags net thread reflector ocaml

 

Why does the directory use F #?
Install F #
Hello, F #
Let expression
Keyword
MPs queue
F # can also process objects
Asynchronous F #
Working with F # as a new member of the Microsoft. NET Framework family, F # provides type security, performance, and working capabilities similar to scripting languages, all of which are part of the. NET environment. This functional language was invented by Don Syme from Microsoft Research Institute as a CLR ocaml syntax compatibility variant, but F # has been quickly transferred from scientific research to practical application. With the concept of functional programming passed. net wildcard and LINQ and other technologies are increasingly infiltrated into mainstream languages (such as C # and Visual Basic), F # In. net community is also growing in popularity-therefore, Microsoft announced in November 2007 that F # was identified as supported.. NET programming language. Over the years, we have always believed that the functional language field (Ml, Haskell, etc.) is more suitable for academic research than professional development. However, this does not mean that these languages are not extraordinary. In fact, some important function enhancements of. Net (such as generic, LINQ, Plinq, and futures) are due to the completely new application of some functional programming concepts to languages. The previous low level of attention to these languages is mainly because their target platform has little to do with developers who write programs for Windows and cannot be well integrated with the underlying platform, or does not support relational database access, XML parsing, and out-of-process communication mechanisms. However, Clr and its "multi-language, single platform" approach will make these languages more and more widely used in Windows development. It is also a matter of course that attracts the attention of first-line programmers. F # is such a language. In this article, I will introduce you to some basic concepts and advantages of F. Then, in order to help you get a preliminary understanding of F #, I will introduce its installation process in detail and write several simple small programs.

 

Why use F #? For a small number of. Net programmers, learning a. NET Framework function language will undoubtedly make a huge step forward in writing powerful software. For other programmers, the reasons for learning F # vary from person to person. F # What benefits can developers provide? With the popularization of multi-core CPUs, secure concurrent programs have become the focus of attention over the past three years. Function language advocates a fixed data structure that can be transmitted between processes and machines without worrying about thread security or atomic access. developers can use this feature to support concurrent operations. Function language also allows you to easily compile a database that supports concurrent features. For example, the F # asynchronous workflow described later in this article. Although programmers who specialize in object-oriented development may not feel so strong about this language, functional programs can simplify the compilation and maintenance of some applications in many cases. For example, compile a program that converts an XML document to data in other formats. Although a C # program can be compiled to parse the entire XML document and apply various if statements to determine the measures taken at different points in the document, but in fact, a better way is to write an extensible style sheet language conversion (XSLT) program. Of course, XSLT certainly contains a large number of built-in function mechanisms, just like SQL. F # We strongly recommend that you do not use null values. Instead, we recommend that you use a fixed data structure. These features can reduce the amount of special code to be written and help reduce the frequency of programming errors. Programs written using F # are more concise. You can reduce the number of inputs in two ways: less keys and less Location Points of variable type, parameter, or return type must be advertised to the compiler. This means that the code to be maintained will be greatly reduced. F # has similar performance characteristics as C. However, compared to a language with similar conciseness (especially those with dynamic and scripting languages), it features much better performance. In addition, F # also contains a tool that allows you to write program segments and interactive execution to view data. This is similar to many dynamic languages.

 

Install F # From research.microsoft.com/fsharp/fsharp.aspx for free. It not only installs all command line tools, but also installs Visual Studio extension packages, the software package provides color syntax highlighting, project and file templates (including detailed F # sample code as the Getting Started Guide), and intelliisense support. It also provides the F # interactive shell that can be run inside Visual Studio. It enables developers to extract expressions from the source file window and paste the expressions into the interactive shell window, and immediately obtain the result of the code segment-display the result in the immediate window similar to the enhancement. When I wrote this column, F # runs in Visual Studio as an external tool, so it lacks the ability of some developers to seamlessly integrate from C # Or Visual Basic. In addition, F # does not support ASP. NET page designer. (This does not mean that F # cannot be used in ASP. NET. This only means that Visual Studio does not provide a ready-to-use drag-and-drop development experience similar to C # and Visual Basic for F .) However, the current version of F # can still be used anywhere in other. Net compatible languages. In the next few pages, you will see some examples.

 

Hello, F # the special way to introduce any language is through the standard "Hello, world" program. F # is no exception:
printf "Hello, world!"
Although it cannot attract you too much interest, however, this small example shows that F # is a language that does not require explicit entry points (both C #, Visual Basic, and C ++/CLI require explicit entry points; this language assumes that the first line of the program is the entry point and will be executed from here. To run this program, the just-getting-started F # developer has two options: compile or explain. Running this program (fsi.exe) in the F # interpreter is very simple. Start fsi.exe from the command line and enter the above line in the prompt, as shown in figure Figure 1. Figure 1 Run 'hello, World' in F # Interpreter'(Click the image to get a larger view) Note that in shell, each statement must end with two semicolons. This is a special requirement of the interaction mode. This method is not required for compiled F # programs. To run this example as a standard. Net executable program, start Visual Studio and create a new F # project (you can find this project in "other project types ). Initially, the F # project contains an F # source file called file1.fs. Opening this file will find a large number of sample F # code sets. View the content to get a rough idea of the syntax structure of F. Replace the entire file with "Hello, world!" as shown above! "Code. Run this application. "Hello, world!" is displayed in the console application window !". If you prefer the command line method, you can use the fsc.exe tool in the \ bin subdirectory of the F # installation directory to compile this code. Note: fsc.exe works in a similar way as most command line compilers. It obtains the source code from the command line and generates executable programs as the result. Most command line switches have related documents. If you have used the csc.exe or cl.exe compiler, you may already be familiar with many of them. However, note that F # currently does not provide perfect support for msbuild. In the current installation version (1.9.3.7 at the time of writing), compilation driven by msbuild cannot be directly supported. If you want "Hello, world !" F # provides complete fidelity and interoperability easily through the CLR platform (including the Windows Forms library. Try the following code:
System.Windows.Forms.MessageBox.Show "Hello World"
Exploitation. the net framework class library and F # library make f # language attractive not only for communities that have long used functional languages such as ocaml or Haskell for mathematics and scientific computing, it is also widely used in the world. NET developers favor.

 

Let expression let's look at the traditional "Hello, world !" More complex F # sample code. See the following code:
let results = [ for i in 0 .. 100 -> (i, i*i) ]printfn "results = %A" results
In the F # syntax, let expressions are curious elements. It is the most important expression in the entire language. More formally, let can assign values to identifiers. In the line of Visual Basic and C # developers, "it can define a variable ". But this is not accurate. In F #, an identifier contains two elements. First, once defined, the identifier cannot be changed. (This Is How f # helps programmers create concurrent security programs because it does not advocate variable states .) Second, the identifier can be not only a primitive type or an object type (for example, the type used in C # and Visual Basic), but also a function type, which is similar to that of LINQ. Note that the identifier is never explicitly defined as a type. For example, the result identifier is never defined; it is inferred from the right side of the following expression. This is called type inference, and it represents the ability of the compiler to analyze code, determine return values, and automatically insert return values (similar to the new C # type inference expression to deduce Using Variable keywords ). Let expressions can not only process data, but also define functions. F # regards a function as the first level. The following example defines an addition function, which uses two parameters A and B:
let add a b =    a + b
Work Exactly as expected: Add a and B and explicitly return the result to the caller. This means that technically, each function in F # will return a value, even if the returned value is not necessarily a value, a special name unit will be returned. This will generate some interesting hints in the F # code, especially the intersection with the. NET Framework class library. Currently, C # and Visual Basic developers can regard unit as the same type as void. Sometimes the function should ignore the parameters passed to it. To achieve this purpose in F #, you only need to use the underline as the placeholder for this parameter:
let return10 _ =    add 5 5// 12 is effectively ignored, and ten is set to the resulting// value of add 5 5let ten = return10 12printf "ten = %d\n" ten
Similar to many functional languages, F # allows currying based on its calls (you can only define partial function applications) to provide other parameters:
let add5 a =    add a 5
To some extent, this is similar to creating an overloaded method that accepts different parameter sets and calls other methods:
public class Adders {    public static int add(int a, int b) { return a + b; }    public static int add5(int a) { return add(a, 5); }}
However, there is a slight difference between the two. Note that the F # version does not explicitly define the type. This indicates that the compiler will use its own type inference method to determine whether the add5 parameter is compatible with the added integer 5, and determine whether to compile in this way or mark it as an error. In fact, the F # language mainly uses implicit type parameterization (that is, generic type ). In Visual Studio, when a pointer is parked on the definition of ten shown above, it indicates that its type is declared:
val ten : ('a -> int)
In F #, this indicates that ten is a value, a function that obtains any type of parameters and generates integer results. The Mark syntax is roughly equivalent to the <t> syntax in C #. Therefore, the most appropriate statement for C # functions is that ten is the delegate instance of the type parameterization method, you want to ignore its type (but it cannot be ignored under the C # rule ):
delegate int Transformer<T>(T ignored);public class App{  public static int return10(object ignored) { return 5 + 5; }  static void Main()  {    Transformer<object> ten = return10;    System.Console.WriteLine("ten = {0}", return10(0));  }}

 

Keyword for now let's take a look at the for keyword in the first example:
#lightlet results = [ for i in 0 .. 100 -> (i, i*i) ]printfn "results = %A" results
First look at the top of the Code. Note # Light syntax. This is a concession for non-ocaml programmers to start using F #, relax the syntax requirements of some ocaml languages, and use a large number of blank definition code blocks. Although not necessary, it does make the syntax easier to parse for common developers who originally used C # Or Visual Basic, therefore, it often appears in F # examples and public code segments, and has become a de facto F # programming standard. (In future F # versions, # light may be determined as the default syntax, instead of other similar methods .) The seemingly simple for loop is actually not simple. Formally speaking, this is another way of saying that a list is to generate a list result code block. The list is a primitive structure that often appears in functional languages. In this respect, it has many similarities with arrays. However, the list does not allow location-based access (for example, the traditional A [I] syntax in C ). The list can appear in different locations of functional programming. In most cases, it can be viewed as. the list <t> In the. NET Framework is similar, but provides the same items for some enhancements. The list usually uses some special types. In this example, the identifier result is an aggregate list, especially F # identifies this aggregation type as a type (int * INT ). If you think of this aggregation list as a pair of columns returned by the SELECT statement in SQL, its meaning is much clearer. Therefore, the example is to create a list of integer pairs containing 100 items. Generally, in Functional Languages, function definitions can be used anywhere where code appears. Therefore, if you want to extend the preceding example, you can write the following code:
let compute2 x = (x, x*x)let compute3 x = (x, x*x, x*x*x)let results2 = [ for i in 0 .. 100 -> compute2 i ]let results3 = [ for i in 0 .. 100 -> compute3 i ]
Traversing a list (or an array or some other repeated structures) is a common task in functional languages. It has become a basic method call: List. ITER. It calls only one function for each element in the list. Other similar library functions provide some very useful functions. For example, list. Map uses a function as a parameter, applies the function to each element in the list, and returns a new list generated by this process.

 

Pipeline let's discuss another structure in F #-pipeline operator, which gets the function result through a channel similar to the shell (such as Windows powershell) pipeline, use the result as the input of the next function. Let's see Figure 2F # code segment. This code snippet uses the system. Net namespace to connect to the HTTP server, obtain the corresponding HTML and analyze the results. Figure 2 search and analyze html
/// Get the contents of the URL via a web request let http(url: string) =   let req = System.Net.WebRequest.Create(url)   let resp = req.GetResponse()   let stream = resp.GetResponseStream()   let reader = new System.IO.StreamReader(stream)   let html = reader.ReadToEnd()   resp.Close()   htmllet getWords s = String.split [ ' '; '\n'; '\t'; '<'; '>'; '=' ] s let getStats site =   let url = "http://" + site   let html = http url   let words = html |> getWords   let hrefs = html |> getWords |> List.filter (fun s -> s = "href")   (site,html.Length, words.Length, hrefs.Length)
Note the words identifier in the getstats definition. It gets the HTML value returned from the URL and applies the getwords function to it. I can also write definition reading:
let words = getWords html
The two are equivalent. However, the hrefs identifier shows the power of the pipeline operator, which can be used to connect any number of applications. Here, I obtain the result list of words and pass it to the list. filter function through pipelines. This function uses the anonymous function to find the word href and return it when the expression is true. In addition, the most important thing is that the getstats call result will be another aggregate (string * int * INT ). To write in C #, more than 15 lines of code are required. Figure 2The following code also shows more F # compatibility with. NET Framework:
open System.Collections.Genericlet capitals = Dictionary<string, string>()capitals.["Great Britain"] <- "London"capitals.["France"] <- "Paris"capitals.ContainsKey("France")
Indeed, this example contains nothing except the exercise dictionary <K, V> type, but shows how to specify the generic type in F # (using the same angle brackets as C), how to use indexes in F # (square brackets are also used in the same way as C #), and how to execute. net (use the same points and parentheses as in C ). In fact, the only new content here is to use the left arrow operator to assign values to variable values. This is necessary, because F # is used for comparison like most functional languages, with equal signs reserved to maintain the meanings of mathematical symbols: If x = Y, the values of X and Y are equal, instead of assigning the value of Y to X. (Real mathematicians have long raised objections to the ubiquitous or imagined x = x + 1, and even sneered .)

 

F # can also process objects. Of course, not all developers who start to use. NET are willing to accept the concept of function immediately. In fact, most developers who have switched from C # Or Visual Basic to F # Need to know that they can retain their original habits when using this new language. To some extent, this is completely feasible. For example, see Figure 3Class Definition of the Two-dimensional vector shown on the top. There are some interesting concepts. First, note that no explicit constructor body exists. The parameters in the first line indicate that the parameters used to construct a vector2d instance are essentially constructor. Therefore, length identifiers and DX and Dy identifiers are private elements of the vector2d type, while the member keyword indicates that the obtained vector2d external available members can be accessed through the standard. Net attribute. Essentially, this section of F # Code declares that you can Figure 3Content shown at the bottom (reported by reflector ). Figure 3 F # And C # vector variants
                                                            VECTOR2D IN F# type Vector2D(dx:float,dy:float) =     let length = sqrt(dx*dx + dy*dy)    member obj.Length = length    member obj.DX = dx    member obj.DY = dy    member obj.Move(dx2,dy2) = Vector2D(dx+dx2,dy+dy2) VECTOR2D IN C# (REFLECTOR> [Serializable, CompilationMapping(SourceLevelConstruct.ObjectType)]public class Vector2D{  // Fields  internal double _dx@48;  internal double _dy@48;  internal double _length@49;  // Methods  public Vector2D(double dx, double dy)  {    Hello.Vector2D @this = this;    @this._dx@48 = dx;    @this._dy@48 = dy;    double d = (@this._dx@48 * @this._dx@48) +                (@this._dy@48 * @this._dy@48);    @this._length@49 = Math.Sqrt(d);  }  public Hello.Vector2D Move(double dx2, double dy2)  {    return new Hello.Vector2D(this._dx@48 + dx2, this._dy@48 + dy2);  }  // Properties  public double DX  {    get    {      return this._dx@48;    }  }  public double DY  {    get    {      return this._dy@48;    }  }  public double Length  {    get    {      return this._length@49;    }  }}
Remember that F # is similar to most functional languages, and constant values and States are recommended. When viewing Figure 3This is especially obvious when the code in, because all attributes are read-only, and the move Member does not modify the existing vector2d, but creates a new copy from the current vector2d, and apply the modified value to the copy before returning it. Note that the F # version not only provides the overall thread security, but also can be accessed through the traditional C # Or Visual Basic code. This provides a simple method for getting started with F #: use it to define business objects or other types that require thread security and are fixed. Although you can create a type that provides common variable operation groups (set attributes and similar operations) in F #, more work is required and the mutable keyword is required. In today's world where concurrency issues have become the main theme of daily work, as many people have asked for, the default value remains unchanged and must or needs to be variable. Creating a type in F # is interesting, but you can still use F # To do the work that traditional C # Or Visual Basic code can do, for example, create a simple windows form application and collect input from the user, as shown in figure Figure 4. Figure 4 Use F # compile Windows Forms
#lightopen Systemopen System.IOopen System.Windows.Formsopen Printflet form = new Form(Text="My First F# Form", Visible=true)let menu = form.Menu <- new MainMenu()let mnuFile = form.Menu.MenuItems.Add("&File")let filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"let mnuiOpen =  new MenuItem("&Open...",    new EventHandler(fun _ _ ->      let dialog =         new OpenFileDialog(InitialDirectory="c:\\",          Filter=filter;          FilterIndex=2,           RestoreDirectory=true)         if dialog.ShowDialog() = DialogResult.OK then          match dialog.OpenFile() with          | null -> printf "Could not read the file...\n"          | s ->            let r = new StreamReader(s)             printf "First line is: %s!\n" (r.ReadLine());            s.Close();    ),    Shortcut.CtrlO)mnuFile.MenuItems.Add(mnuiOpen)[<STAThread>]do Application.Run(form)
Any developer familiar with Windows Forms can immediately understand the meaning of the Code: create a simple form, fill in some properties, fill in an event handler, and tell the application to start running, until the user clicks the close button in the upper-right corner. Because the standard elements are the same as those of. NET applications, you only need to focus on the F # syntax. The operation of an open statement is roughly the same as that of the using statement in C #. In essence, it is used to open the. NET namespace for use without a formal limitation. The printf namespace is the original F # port with the same name as the ocaml module technically. F # not only has a complete. NET Framework class library, but also has the simplest ocaml library port, which allows programmers familiar with the language to use it as they do with. NET Framework. (Curious programmer: printf is located in the fsharp. Core. dll program set .) You can use system. Console. writeline at any time based on your preferences. The creation of form identifiers uses the F # naming parameter, which is equivalent to instantiating an object, and then calls a series of attribute sets to fill these attributes with values. In the following lines, I use the same method to create a dialog box identifier. Definitions of mnuiopen identifiers include interesting structures that are no stranger to developers familiar with. NET Framework 2.0 anonymous delegation or lambda expressions in. NET Framework 3.5. When constructing the eventhandler associated with open menuitem, you can see the anonymous function defined using the following syntax:
fun _ _ -> ...
Similar to anonymous delegation, this Code creates a function that will be called when the menu item is selected, but the syntax is slightly tricky. In the menuitem definition, eventhandler is defined to ignore the anonymous functions of the two parameters passed to it. These two parameters cleverly correspond to the sender and event parameters in the standard eventhandler delegate type. This function requires that a new openfiledialog be displayed and check the result when you click "OK"... as shown below:
if dialog.ShowDialog() = DialogResult.OK then    match dialog.OpenFile() with    | null -> printf "Could not read the file...\n"    | s ->        let r = new StreamReader(s) in        printf "First line is: %s!\n" (r.ReadLine());        s.Close();
The results of the pattern matching check will be used. This method is a powerful function in the world of functional languages. On the surface, pattern matching is similar to switch/case in C # in some places, but it actually completes pattern matching: it compares values with various modes (these modes do not need to be constant values) and executes matching code blocks. Therefore, the matching block shown in this section is used as an example. openfile results can match two possible values: NULL indicates that no file can be opened or any non-null value S is allocated, this value is then used as the constructor of streamreader to open and read the first line of the given text file. Pattern matching is an important part of most functional languages. It is worthwhile to do some research on it. One of its most common uses is to work with the identifiable Union (discriminated Union) type (C # Or an inaccurate description of the enumeration type in Visual Basic:
// Declaration of the 'Expr' typetype Expr =   | Binary   of string * Expr * Expr  | Variable of string   | Constant of int// Create a value 'v' representing 'x + 10'let v = Binary("+", Variable "x", Constant 10)
Function languages are often used to create the core representation of a specific domain language. developers can use it to write more complex and powerful structures. For example, it is hard to extend this syntax to create a fully computed language and to expand it simply by adding new elements to the expr type. Note that the * character syntax does not indicate multiplication. It is a standard method used in functional languages to indicate that a type contains multiple parts. In fact, functional languages have been widely used in programming tools for programming (such as interpreters and compilers), and the expr type will eventually become a complete set of language expression types. F # Two built-in tools: fslex and fsyacc (designed for obtaining traditional language input-Lex and YACC files-and compiling them into F # code for simplified operations) make it easier. If you are interested in this, you can download the F # installer for in-depth research. In particular, the parsing example in the standard F # release package provides a very good entry infrastructure. Identifiable union is only one of the advantages of pattern matching. Another advantage is expression execution, such Figure 5. REC located in the eval definition is required, and it tells F # the compiler to call eval iteratively within the defined subject. Without it, F # expects a local nested function named eval. In actual use, I use the getvarvalue function to return some predefined values for the variable. getvarvalue will check the dictionary to find the returned values determined during variable creation. Figure 5 expression execution
let getVarValue v =    match v with    | "x" -> 25    | "y" -> 12    | _ -> 0let rec eval x =    match x with    | Binary(op, l, r) ->        let (lv, rv) = (eval l, eval r) in        if   (op = "+") then lv + rv         elif (op = "-") then lv - rv         else failwith "E_UNSUPPORTED"    | Variable(var) ->         getVarValue var    | Constant(n) ->        ndo printf "Results = %d\n" (eval v)
When Eval is called, it obtains the value V and finds that the value is a binary value. This matches the first subexpression. This expression then binds the value (LV, RV) to the calculated results of the left and right sides of the binary value just checked. An unnamed value (LV, RV) is an aggregation (essentially a single value representing multiple parts), which is similar to a relational set or a C structure. When eval L is called for the first time, the L from the binary instance happens to be of the variable type, so the recursive call to eval matches the branch of the matching block in this pattern. Then, getvarvalue is called, and a hard-coded value of 25 is returned. The value is bound to the value LV. For constant R with a value of 10, the order is the same, so it is bound to the RV. Then execute the remaining part of the code block (if/else-If/else block). Developers familiar with C #, Visual Basic, or C ++ can easily understand the meaning of the code block. It should be emphasized that each expression returns a value, even inside the pattern matching block. In this example, the return value is an integer value, which may be the calculated value, the value retrieved from the variable, or the constant itself. This seems to make it easier for developers accustomed to object-oriented or procedural programming to produce microterms, because in C #, Visual Basic, or C ++, the return value is optional, you can ignore the returned value even when the returned value is specified. In Functional Languages similar to F #, explicit encoding is required to ignore the returned values. In this case, the programmer can pass the result to a function named ignore for proper operations.

 

Asynchronous F # so far, I have introduced the F # syntax in either of the following two ways: or use a relatively simple functional structure, or make it look relatively elementary and concise, such as traditional object-oriented ,.. Net compatible language (C #, Visual Basic, or C ++/CLI. This introduction is hard to promote the adoption of F # in enterprises #. But take a look Figure 6. It can be different from the previous two forms. In addition to multiple appearances! And use the async modifier. This is a relatively intuitive piece of code: load the source image, extract its data, pass the data to an independent function for processing (rotation, stretching, or other operations), and write the data back to the output file. Figure 6 process images
let TransformImage pixels i =  // Some kind of graphic manipulation of imageslet ProcessImage(i) =  async { use  inStream  = File.OpenRead(sprintf "source%d.jpg" i)          let! pixels    = inStream.ReadAsync(1024*1024)          let  pixels'   = TransformImage(pixels,i)          use  outStream = File.OpenWrite(sprintf "result%d.jpg" i)          do!  outStream.WriteAsync(pixels')          do   Console.WriteLine "done!"  }let ProcessImages() =  Async.Run (Async.Parallel                [ for i in 1 .. numImages -> ProcessImage(i) ])
Obviously, the async modifier is used to make the code into the asynchronous workflow called F # (not related to Windows Workflow Foundation, this means that each step of these loading/processing/saving steps is in.. Net thread pool parallel thread execution. To make it simpler, take a look. Figure 7. This special sequence shows asynchronous workflows in a relatively simple and easy-to-understand manner. Without going into the details, we can see that evals is a group of functions to be executed. By calling async. Parallel, each function is queued in the thread pool for execution. During execution, we can see that the functions in evals are actually in different threads than those in AWR (although due. net System thread pool features, some or all evals functions may be executed in the same thread ). Figure 7 asynchronous function execution
#lightopen System.Threadinglet printWithThread str =    printfn "[ThreadId = %d] %s" Thread.CurrentThread.ManagedThreadId str    let evals =    let z = 4.0    [ async { do printWithThread "Computing z*z\n"              return z * z };      async { do printWithThread "Computing sin(z)\n"              return (sin z) };      async { do printWithThread "Computing log(z)\n"              return (log z) } ]let awr =    async { let! vs = Async.Parallel evals            do printWithThread "Computing v1+v2+v3\n"            return (Array.fold_left (fun a b -> a + b) 0.0 vs) }let R = Async.Run awrprintf "Result = %f\n" R
The execution of these functions outside the. NET thread pool again shows that the F # language has excellent support for runtime interoperability. Even functional languages that were previously reserved for special implementations (such as threads) need to be dependent. net Framework class library, which indicates that C # programmers can use the F # library or module, just as F # developers can use the C # library. In fact, in the future, F # functions (such as Asynchronous tasks) will be able to make full use of the new. NET Framework library (such as the task processing library in the parallel extension library ).

 

If cooperation with F # is not very clear about F #, there are still many introductions about F # language, which are far beyond the scope of an article. In fact, between the new method and the New Way of Thinking (functional and procedural), frankly speaking, for general developers who are used to object-oriented such as C # Or Visual Basic, it takes some time to master f. Fortunately, F # is fully interoperable with other languages in the. NET system, which means that you can use many existing knowledge and tools to help you change F # Into your own programming tool. F # developers can access all the base class libraries, and because F # supports some procedural and object-oriented development, you can completely consider not compiling, use the F # interaction model to learn F # syntax and the details of Windows Presentation Foundation, Windows Communication Foundation, or Windows Workflow Foundation. As mentioned above, developers can write the Business Objects used by other parts of the supplied program code in F. Because most of the classes generated by F # type construction are similar to those constructed by C # Or Visual Basic, the persistent libraries such as nhib.pdf can still retain the F # type smoothly, so that F # Can be seamlessly injected into other business applications in use. You only need to learn some F # knowledge to help you better understand many new features of C # and Visual Basic in future versions, because many of these ideas and concepts-including generics, iterators (yield keywords in C #), and LINQ-are derived from functional and F # team's research. No matter what you think of functional programming, it is already a fact and will continue to function.

 

Ted newardIs an Expert independent consultant in the field of advanced enterprise systems. He has written (or co-authored) Multiple books and is also a Microsoft MVP architect, BEA Technical Guidance, ineta lecturer, and pluralsight trainer. You can contact Ted's blog blogs.tedneward.com through a ted@tedneward.com.

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.