F # basic syntax-keywords and structures [z]

Source: Internet
Author: User

Source: http://lorgonblog.spaces.live.com/blog/cns! 701679AD17B6D310! 887. entry

Translated by Mike

I have written many blog posts about F #, but I have not described the basic syntax of F # language so far. so today I will try my best to make up for this defect and describe some of the keywords and syntax structures that are common in F # code. this blog does not cover all F # syntaxes, but covers about 75% of common syntaxes. in order to make this article as simple as possible, I may intentionally make a small mistake in the overall accuracy.

# Light

Most F # files start with "# light"

(Note: In the current Dev10 version, "# light" has been set to open by default, so the current F # file does not need to be displayed and called "# light ")

# Light

This is used to open the "lightweight syntax" option. I will not discuss the options corresponding to the "lightweight Syntax" here, because people always use the "lightweight Syntax" option. in the next F # version, "lightweight Syntax" will become the default option (Note: The current F # version has already done so ). make sure that "# light" always appears at the beginning of the F # code file.

Comments

There are two types of annotations. See the following code.

// A one-line comment

(* A multi-line
Comment (* these can nest *)*)

"Open" -- open a namespace

The "open" keyword is used to open a namespace or module.

// Must fully qualify the name System. Console
System. Console. writeline ("Hello, world! ")

// After opening the namespace, don't need
Open System

Console. writeline ("Hello, world! ")

"Let"-define functions and values

The "let" keyword is used to define functions and values. Here are some examples of using "let" to define values:

Let X = 42 // immutable, X is always 42
Let mutable y = 0 // mutable, can re-assign y's value with <-Operator
Let Z: String = NULL // ": string" is type annotation to declare type

You rarely use the type description (F # Is a type inference language), but in the last example, the type inference is necessary (if you do not use the type description, 'Z' will be inferred as "OBJ" (system. object) type. The type description here tells the compiler that 'Z' is a "string" type ).

The following are some examples of using 'let' to define a function:

Let f x = x + 1
Let g x Y = x + y
Let G2 (X: Float) (Y: Float): Float = x + y
Let h (x, y) = x + y
Let rec kaboom x = kaboom (x + 1)

"F" is a function with a parameter. "G" and "G2" have two colized parameters (the type description specified for the parameter in "G2" is the type description specified for the return value of the function, and this syntax is displayed ), however, "H" uses the tuple parameter. To learn more about tuples and colialization, you must read this blog. in addition, the 'let rec 'keyword can define a recursive function.

Lightweight syntax makes space characters/indentation more meaningful, and indentation is the most common method to define the range of functions (and other struct. in addition, the function can be defined anywhere. the following code illustrates the above points:

Let Area diameter = // define a function
// Everything indented under here is the body of "Area"
Run pi = 3.14 // define a value inside the function
Let Radius d = // define another function inside here
// This is the body of the "Radius" function
D/2.0
Let r = Radius diameter
Pi * r

// Use the function
Let answer = Area 5.0

"Fun" -- lambda expression is "fun" here"

The "fun" keyword is used to define lambda (anonymous functions. the syntax is "fun parameter-> function body", and priority rules often force you to put all definitions in a pair of parentheses. See the following example:

Let nums = [1; 2; 3; 4; 5]
Let odds = List. filter (fun x-> x % 2 = 1) nums
Printfn "odds = % A" odds // odds = [1; 3; 5]

In this example, note that '%' is a modulo operator, used here to determine whether the number 'X' is an odd number, List. filter is a function that applies assertions to a list (a Boolean function is returned). It returns a list of elements that return true values through an asserted function.

"|>" Pipeline operator

A frequently used built-in operator is pipe. "x |> f", which is "f x". Therefore, the above example is more accustomed to writing as follows:

Let nums = [1; 2; 3; 4; 5]
Let odds = nums |> List. filter (fun x-> x % 2 = 1)
Printfn "odds = % A" odds // odds = [1; 3; 5]

In fact, using the pipeline operator in this small example does not have any substantial benefits, but this operator is often used to "pass" data in a series of conversion functions. for more details, see here.

"Match" pattern match

Pattern matching is a very powerful language feature that can be used in many environments, but it is most often used in 'match' expressions.

MatchExprWith
|Pat_1->Body_1
...
|Pat_n->Body_n

This expression tests each pattern, and the method after the first pattern to be matched is executed. the most common pattern includes a simple algebraic data type, such as discriminate Union, especially for matching a list or an optional value; for the description of the identifiable Union and how to match the identifiable Union, see the first half of this article. (I will probably write at least two complete articles about pattern matching at the end, but the descriptions in the above and link articles are sufficient for you, because here you only need to have a quick understanding of the language .).

Conditions and loops

Although F # uses less than other languages (pattern matching and recursive substitution are generally used), F # still contains if-then-Else and while loops, for loop. F # is a functional language, so these are expressions with return values.

The following is the general syntax of if-then-Else.

IfCond1Then

Expr1
ElifCond2Then

Expr2
Else

Expr3

The 'elif' and 'else' sections are optional, and you can use either of them. all exprn values must be of the same type, which is also the type of the return value of the entire expression. if the 'else' part is omitted, the exprn must be of the 'unit 'type (it is a close relative of "Void ).

The while syntax is:

WhileCondDo
Expr

The while expression always returns "unit". In F #, there is no such thing as "break" or "continue.

ForPatInExprDo
Bodyexpr

Here, expr is something you can traverse (such as: ienumerable <t>, seq in F # <'a> ), pat is a pattern (but the most common is a new identifier name). bodyexpr executes each element during traversal. for example:

For X in somearray do
Printfn "% d" x

Print All integers in the "somearray". The entire 'for 'expression returns the 'unit' type like the 'while.

"New"-use "new" to create an object

You can use "new" to create an object just like in C.

Let X = new system. Uri ("http://hello.world /")

However, the 'new' keyword in F # is usually an option.

Literals)

There are many types of literal in F #, the most common of which are the following:

Let B: bool = true // or false
Let I: Int = 42
Let s: String = "hi"
Let X: Float = 3.14 // "3." Same as "3.0"
Let AI: int array = [| 1; 2; 3 |] // "int array" = "array <int>"
Let lf: Float list = [1.1; 2.2; 3.3] // "float list" = "list <float>"

(All types here are not necessary, but they are very helpful for my explanation .) boolean, integer, and string Literal will work as expected. "Floating Point" is equivalent to System. double is a numeric constant that contains the decimal point. array constants are written using [| parentheses |], while list constants are written using [parentheses]. They all use semicolons (or separate rows) To differentiate elements in the set. only the most common types are shown here. I will discuss more F # built-in types in detail in the new blog.

Exception constructs

F # has a "try-catch-finally" structure and uses IDisposable in C #. Its basic syntax is:

Try
Expr
With
|Pat_ I->Body_ I
Try
Expr
Finally
Cleanup
UseIdent=Expr

For more information, see here.

What else is not described?

Apart from types (new types, classes, members, and so on are defined; including built-in types that describe uncommon) and pervasives (built-in operators and functions ), this introduction covers almost 95% of F # common syntax structures. type and pervasives I plan to explain in my future blog.

Original: http://blog.joycode.com/fscti/archive/2009/10/21/115741.joy

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.