Lists (list) are the basis of functional programming (FP). In fact, the name of Lisp, the important representative of FP, originates from "List processing," a paper published in 1960 by its inventor, John McCarthy, shows us, based on a few simple operators and a notation that represents a function, One of the main ideas of how to construct a complete programming language is to use a simple list of data structures to represent code and data.
The list (linked list) is one of the main data structures of Lisp, and the source code of Lisp itself is made up of lists. List types in F # are represented as linked lists, which are significantly different from arrays in C #, generic list<t> types. The list can be expressed in the following figure:
First, let's take a look at the basic operation of the list in FP (where the code is implemented by F #).
Basic operation of a list
Cons: It is the abbreviation for "construct", which is used to construct the list, meaning an element is added to the beginning of the list. Let's start by agreeing that the empty table is represented as [], and on this basis, the operator "::" represents the cons operation, so that we can construct any list. Such as:
F# Code - 列表的cons操作
let emptyList = [] // []
let oneItem = 3 :: [] // [3]
let twoItems = 2 :: oneItem // [2; 3]
let threeItems = 1 :: twoItems // [1; 2; 3]
You can see how this is done through the "cons" operation to construct the list step-by-step.
Car: It means "Contents of the", the "Register", meaning the first element of the list. The HD (head) function of the list module is used in F # to perform the car operation:
F# Code - 列表的car操作
let stringList = ["No "; "one "; "really "; "listens to "; "anyone else."]
List.hd stringList // "No "
CDR: It means "Contents of the" decrement part of the Register, meaning an element other than the first element in the list. The TL (Tail) function of the list module is used in F # to perform a CDR operation:
F# Code - 列表的cdr操作
let stringList = ["No "; "one "; "really "; "listens to "; "anyone else."]
List.tl stringList // ["one "; "really "; "listens to "; "anyone else."]
With these three basic operations, other operations can be deduced. Like what:
Concat: This operation is used to connect two lists. The operation is performed with the "@" operator in F #.
F# Code
let list1 = [2; 3; 4]
let list2 = [5; 6; 7]
let largeList = list1 @ list2
print_any largeList // [2; 3; 4; 5; 6; 7]
Length: The number of elements in the check list, using the length function of the list module in F #:
F# Code
let list1 = [2; 3; 4]
List.length list1 // 3
Nth: This action returns the nth element of the list, using the nth function of the lists module in F #:
F# Code
let list1 = [2; 3; 4]
List.nth list1 2 // 4
Here the code is used to get the index in List1 (based on 0) to 2, and returns 4.