F # Adventure (2): functional programming (medium)

Source: Internet
Author: User

Operator)

In F #, operators can be seen as a more elegant way to call functions. There are two types of operators: prefix and infix. The former accepts an operand before the operand. The latter accepts two or more operands, it appears between the first two operands.

F # provides a rich set of operators for numbers, Boolean values, strings, and set types. These operators are numerous and limited in space. I will not explain them here. This article focuses on how to use and define operators.

Operators similar to C # And F # can also be overloaded. That is to say, we can apply different types to the same operator, such as "+". But unlike C, each operand must be the same class.
Type. The operator overloading rules of F # are similar to those of C #. Therefore, any class that supports Operator Overloading in the. NET class library compiled by bcl or C # also supports overloading in F.

letwords="Tolive"+"is"+"tofunction."
openSystem
letoneYearLater=DateTime.Now+newTimeSpan(365,0,0,0,0)

We can define our own operators or redefine any existing operators (this is not recommended ). Take a look at the following bad practices:

let(+)ab=a–b
print_int(1+2)

What do you think of here? Are you sure you want to define a function! Therefore, we mentioned above that "operators can be seen as a more elegant way of function calling ". We have redefined "+"
Operator, so "1 +
The result of 2 "is-1, which of course has no benefit. How can I change" + "to its original meaning when using FSI in? I usually turn off the FSI process in the task manager, and press enter, "+"
It will be back.

The custom operator cannot contain letters or numbers. The following characters can be used:

!$%&+-./<=>?@^|~
:

The first character of the operator can be any character in the first line above, and the subsequent character can be any character above. The definition syntax is similar to the function, except to include operations. See the following example:

let(+^*)ab=(a+b)*(a*b)

The result is 30.

List (lists)

List is a simple set type built in F. It can be an empty table (empty list), represented by square brackets ([]). We can connect a value to the list. In this case, we need to use the ":" operator. Note that we need to use the value as the first operand:

letemptyList=[]
letoneItem="one"::[]
lettwoItem="two"::oneItem

In vs, we can see that the oneitem type is string list. If the list contains multiple items, it is troublesome to use the above method. We can use the following syntax:

letshortHand=["hello";"world!"]

In addition, we can use the "@" operator to connect two lists:

letconcatenateLists=["one,";"two,"]@["three,";"four"]

F # The Element Types in the list must be the same. If you really need to list elements of different types, you have to create an OBJ (system. Object) type list:

letobjList=[box1;box2.0;box"three"]

The third box is optional, which reminds me of the packing in C.

The list in F # cannot be modified. Once created, it cannot be modified. The functions and operators acting on the list cannot modify the list, but create a copy of the list. This feature is similar to the string type in C. See the following example:

#light
letprintListlist=
  List.iterprint_stringlist
  print_newline()
letthreeItems=["one";"two";"three"]
letreversedList=List.revthreeItems
printListthreeItems
printListreversedList

The ITER method above accepts two parameters. The first is the function, and the second is the list. The function is used to apply the function to each element of the list in sequence, a bit like the foreach loop in C. The Rev method returns the reverse list of the list.

The output is as follows:

one tow three
three two one

Neither of the above methods has changed the original list. For more information about the F # list, read this article mastering F # lists.

 

List Derivation)

The concept of list derivation is derived from mathematics, which makes it easy to create and convert a set. In F #, you can use this derivation syntax to directly create a list, sequence and array (sequence and array will be described later ). For more information about this concept, see list_comprehension.

The simplest case is to specify the list range, for example:

letnumericList=[0..9]
letcharList=['A'..'Z']

The two lists are of the int list and char list types, ranging from 0 to 9 and from 'A' to 'Z '.

A more complex case is to specify a step:

letmultipleOfThree=[0..3..30]
letrevNumericList=[9..-1..0]

The value of the first list is a multiple of all 3 from 0 to 30, and the element of the second list contains 9 to 0.

We can also obtain another list by repeating one list. For example:

letsquares=[forxin1..10->x*x]

Loop through for. The elements in the squares list are the squares of integers ranging from 1 to 10.

In addition, you can add the when clause to filter elements in a loop. Only when the value of the when clause is true:

letevens=[forxin1..10whenx%2=0->x]

The evens element is [2; 4; 6; 8; 10].

Control Flow)

F # has a strong control process concept, which is different from many pure functional programming languages. Expressions in these languages can be evaluated in any order. See the following example:

letabsoluteValuex=
  ifx<0then
    -x
  elifx=0then
    0
  else
    x

If, Elif, then,
We should be familiar with the structure composed of else. In F #, this structure is an expression, that is, it needs to return a value. And the value returned by each branch should have the same type. Otherwise, a compilation error occurs.
Error. If you do want to return multiple types of values, add the box keyword before the value, as in the previous creation of the list, so that the return type of the expression is obj.

 

Types and type inference)

F # is a strongly typed language. The value passed to the function must be of the specified type. If a function accepts a string type parameter, it cannot be passed to its int type value. A language is called a language type system to process the value type. The Type System of F # is different from the general language. All values, including functions, have their own types.

Generally, we do not need to explicitly declare the type. the compiler will try to judge its type from the text value of the value or the type returned by the called function. This process is called type derivation. You can use the-I switch during compilation to display all the derivation types. In vs, you can use a tooltip to view the types of identifiers. Let's first look at the type derivation of the nominal value:

letstrValue="StringValue"
letintValue=12

In FSI, the following information is displayed:

valstrValue:string
valintValue:int

It is understandable that the compiler derives its type from the literal value assigned to the identifier. Let's look at the following functions:

letmakeMessagex=(string_of_boolx)+"isabooleanvalue"
lethalfx=x/2

In FSI, the following information is displayed:

valmakeMessage:bool->string
valhalf:int->int

Interestingly, there is also a Val before the function name, which indicates that the function is also a value, followed by bool->
What does string mean? It indicates that the function accepts the bool type parameter and returns the string type value. Note that X is used as the string_of_bool parameter, So X must be
Bool type. The return value is the sum of two strings. Therefore, the return value is also of the string type. For half functions, the X type cannot be determined by a single slave definition. In this case, the compiler uses the default type.
Int. Let's take a look at the complex situation:

letdiv1xy=x/y
letdiv2(x,y)=x/y

The information of these two functions is:

valdiv1:int->int->int
valdiv2:int*int->int

The div1 function can accept some parameters (KE Lihua), while div2 must input two int type values at the same time. Consider the following functions:

letdoNothingx=x

The information is:

valdoNothing:'a->'a

A'-> a' indicates that the function accepts any type and returns a value of the same type as it. Variable type (variable)
Type). Although the compiler cannot determine the type parameter, it can determine that the type of the returned value must be the same as that of the parameter. This feature of the type system is called type parameterization, And the compiler can also find more types.
Error. The concept of variable type or type parameterization, similar to. net
2.0 wildcard. If F # is based on CLI that supports generics, it will take full advantage of generics. In addition, Don Syme, the creator of F #, is the designer and implementer of the generic type in CLR.

The Type derivation of F # is powerful, but it obviously cannot tell the developer's mind. What should I do if I have special requirements? See the following example:

letdoNothingToFloat(x:float32)=x

Float32 is system. Single. Here we manually specify the X type, which is sometimes called type annotation ). If you want to use a class library written in other. NET languages in F # Or interoperate with a non-hosted class library, it will be very useful.

Summary

In the previous article, we will continue to introduce the functional programming paradigm in F #, including operators, lists, list derivation, type derivation, and type annotation. Type derivation is also called implicit type, usually --
But not limited to the features of functional programming languages. For example, C #3.0 and VB. NET 9.0 provide some support, which makes many programming tasks easier.

Refer:

Foundations of F # by Robert Pickering

F # specs: http://research.microsoft.com/fsharp/manual/spec2.aspx

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.