F # (1)

Source: Internet
Author: User
Tags comparison table

Simple Introduction

F #(like C #, read "F sharp") is based on a. NET Framework is a strongly typed, statically typed, functional programming language.
C # can be said to be an object-oriented programming language with functional programming, and F # is a functional programming language that contains object-oriented.
You can view the official documentation for more information.

This series of articles assumes that you are aware of C # and that you are explaining the similarities and differences between F # and C #, allowing readers to quickly learn about F # in a systematic way.
Caishuxueqian, mistakes are unavoidable, if you have any suggestions or comments during the reading process, please feel free.

Functional programming has been tepid over the years, but after knowing that F # is understood, there is a deeper understanding of C #, and it's easy to learn about other functional languages.

Hello, World

When you use F #, you can create a console project like C # to test.
But because F # supports running as a script, it is most convenient to directly open F # Interactive(the FSI) for interaction.

In Visual Studio, you can open in view-other Windows . in the past, when there was no CSI, the FSI was used to test C # code, and CSI was finally added to the VS2015.
If you do not want to open the bloated vs, you can find the FSI at the installation location of the Microsoft SDK. Here is where I installed the FSI for F # 4.0:

"C:\Program Files (x86)\Microsoft SDKs\F#\4.0\Framework\v4.0\Fsi.exe"

A unique way to introduce any language is through that almost standard "Hello, World" program.
The F # output can use printf functions, as follows:

printf "Hello, world!"

Of course, you can also use. Net Console output functions like C #:

System.Console.Write("Hello World")

When the above code is tapped into the FSI, it will be found to be unresponsive because the commit code in the FSI must end with a ;; double semicolon.
Please enter printf "Hello, world!";; and System.Console.Write("Hello World");; or enter again after the line break ;; .

F # Foundation types

Below, we try to convert the following simple C # code into F # code:

int sum = 0; for (int i = 0; i<=100; i++) { if (i%2 != 0) sum += i; } Console.WriteLine("0到100中的奇数的和为{0}", sum);

This imperative code simply adds the odd numbers from 0 to 100, and outputs them.
Although the function is also supported in C #, here we use simple statements to understand the basic syntax.

The following is the F # version of the code:

do    if i%2 <> 0 then sum <- sum + i printfn "0到100中的奇数的和为%A" sum ;;

The result of the above code operation in FSI is:

0 to 100 odd and 2500
Val mutable sum:int = 2500
Val it:unit = ()

As you can see, the end of each line of code in F # ; is optional.

Because one of the features of the functional programming language is the absence of side effects (no Side Effect), immutable (immutable), there is no concept of variable (Variable), only the concept of value .
So in the above run results, all start with Val, and the value it defaults to the last run result, in this case its type is unit , the equivalent of C # void , that is, no return value.

However, in many scenarios, Mutable (variable) can bring a lot of convenience, especially in scenarios like the above with imperative programming.
In the above code, it is val mutable sum a variable value.

Base type

The following is a comparison of the data type definitions for C # and F #:

Data Type C # F #
Int int i = 0; Let i = 0
Let i = 0l
Uint UINT i = 1U; Let i = 1u
Let i = 1ul
Decimal Decimal d = 1m; Let D = 1m
Let d = 1M
Short Short C = 2; let c = 2s
Long Long L = 5L; Let L = 5L
unsigned short ushort C = 6; Let C = 6us
unsigned long ULONG d = 7UL; Let d = 7UL
Byte byte by = 86; Let by = 86y
Let by = 0b00000101y
Let by = ' a ' B
unsigned byte SByte SBY = 86; Let SBY = 86uy
Let SBY = 0b00000101uy
bool BOOL B = true; Let B = True
Double Double d = 0.2;
Double D = 0.2d
Double d = 2e-1
Double D = 2
Double D0 = 0
Let d = 0.2
Let d = 2e-1
Let D = 2.
Let D0 = 0X0000000000000000LF
Float float F = 0.3;
Foat f = 0.3f;
float F = 2;
float F0 = 0.0f;
Let F = 0.3f
Let F = 0.3F
Let F = 2.f
Let F0 = 0X0000000000000000LF
native int IntPtr n = new IntPtr (4); Let n = 4n
unsigned native int UIntPtr n = new UIntPtr (4); Let n = 4un
Char char c = ' C '; Let C = ' a '
String String str = "abc\n";
String str = @ "C:\filename";
Let str = "abc\n"
Let str = @ "C:\filename"
Big int BigInteger i = new BigInteger (9); Let i = 9I

F # Literal details can be viewed in the MSDN article.

Hex, octal, and binary

We know that in C #, hexadecimal values can be defined with a 0x prefix.
In F #, in addition to the 16 binary ( 0x ), you can also define the values of octal ( 0o ) and binary ( 0b ) directly.

let hex = 0xFABClet oct = 0o7771Llet bin = 0b00101010y;;

The output is:

Val Hex:int = 64188
Val Oct:int64 = 4089L
Val Bin:sbyte = 42y

Floating point number

Note that in F #, double and float both represent double-precision floating-point numbers , a single-precision floating-point number is called float32 .
StringThere is also a literal representation method that is three double quotes:

"""<book title="Paradise Lost">    <content /></book>"""

When used @ as a prefix (known as a verbatim string), the double quotation marks within the string must be escaped with two double quotes, using three double-quote notation to avoid the problem.
This notation is most commonly used to encode XML documents into code files.

byte array

In the Type comparison table, a byte line can see a syntax for creating a byte array:

let asciiBytes = "abc"B  // val asciiBytes : byte [] = [|97uy; 98uy; 99uy|]

Its equivalent C # code is:

byte[] asciiBytes = Encoding.ASCII.GetBytes("abc");

Of course, only ASCII encoding is supported.

Variable name

The variable name naming rules for F # are basically consistent with C #, but you can also include single quotes in variable names :

let x = 10let x‘ = 11let Tom‘s = "2010"

By let keyword, 10 bind (assign) to x , 11 bind to x‘ .

In C #, to use a keyword or reserved word as a variable name, you can add a variable name before it @ :
For example, using code

class @class {}

Defines a class that is named classes.

You `` can specify any string as a variable name before and after adding it:

let ``let`` = 4let ``I love F#`` = "This is an F# program."(* 在fsi的输出结果为: val let : int = 4 val ( I love F# ) : string = "This is an F# program."*)

Note In F #, single-line comments are used just like C # // , but multiline comments are (* *) used .

F # operators are similar to C #, and some of the differences are described in the next article. Interested in the FSI can try to enter the operation to play a play, perhaps you can find the difference.

F # (1)

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.