Chapter3-list comprehensions

Source: Internet
Author: User

This time, we will introduce some convenient methods for list initialization and operations.

You can use some special syntax for initialization.List, SequencesWith arrays (list we will know, and Sequences

Corresponding to the ienumerable type of. Net, which will be described later in arrays)

 

The simplest way to initialize a continuous list is to use.... Let's look at the example.

 

LetNumericlist = [0..9]

//Numericlist is ~ List of 9 [0; 1; 2; 3 ......; 9]

LetAlpherseq = {'A'..'Z'}

//Alphersql is a sequence from A-z

LetMultiplesofthree = [0..3..30]

//Returns a multiple of all three starting from 0.

//[0; 3; 6; 9; ......; 27; 30]

LetRevnumber = [9..-1..0]

//The returned result is [9; 8; 7; 6; 5; 4; 3; 2; 1; 0].

 

It can be seen that in [x .. y .. Z], X is the initial value, Y is the step size, and Z is the end value.

That is, the final list will be[X; X + Y + y... z]Until z = x + (? * Y)

 

Another initialization method is to add conditions by using loops;

LetSquares =
[ForXIn 1..10 ->X * x]
//Get 1 ~ A list of the squares of all digits of 10

//Let evens n =

//[For X in 1. n when x % 2 = 0-> X]

//This provided by the author is no longer applicable.

//Built-in functions are recommended.

//The following is a collection of the various knowledge introduced earlier to implement the expression of the above statement of the original author.

LetEvens =FunN->List. Filter (FunX->X %2=0)[0.. N]

Call evens like this

Evens 10

//Returns 0 ~ All even numbers of 10

 

Then there is another,

 
//Let squarepoints n =

//{For X in 1. n

//For Y in 1. N-> x, y}

//Similarly, this method is no longer available in F #2.0, but should be changed:

LetSquarepoints n = [ForXIn 1. NDo

ForYIn 1. NDo

Yield X, Y]

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.