FSharp-03-Collections
List
**List元素默认不可变**
定义List
let list = []
,空Listlet list = [1..10]
,默认步长的Listlet list = [1..2..10]
,步长为2的Listlet list = [1;2;3]
,给定元素的List- 注意
list = [1,2,3]
则是元组
exapmle
1 | // 定义List |
index | value |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
5 | 6 |
6 | 7 |
7 | 8 |
8 | 9 |
9 | 10 |
1 |
|
1 | // 步长-2 |
index | value |
---|---|
0 | 10 |
1 | 8 |
2 | 6 |
3 | 4 |
4 | 2 |
5 | 0 |
切片操作
1 | let list = [0..10] |
index | value |
---|---|
0 | 1 |
1 | 2 |
1 | let list = [0..10] |
index | value |
---|---|
0 | 0 |
1 | 1 |
2 | 2 |
1 | let list = [0..10] |
index | value |
---|---|
0 | 5 |
1 | 6 |
2 | 7 |
3 | 8 |
4 | 9 |
5 | 10 |
1 | let list = [0..10] |
(empty)
1 | let list = [for i in 0 .. 10 -> i*i] |
index | value |
---|---|
0 | 0 |
1 | 1 |
2 | 4 |
3 | 9 |
4 | 16 |
5 | 25 |
6 | 36 |
7 | 49 |
8 | 64 |
9 | 81 |
10 | 100 |
遍历
API
- list[1]
- list.Item(1)
- list.IsEmpty
- list.Length
- list.Head
- list.Tail
- List.contains 1 list
example
1 | let list = [1; 2; 3] |
拼接
API
- 用
::
拼接元素- 用
@
连接两个List- List.zip list1 list2
- let list4, list5 = List.unzip list3
example
1 | // List使用;分隔,用'[]'包住 |
1 | // zip |
index | Item1 | Item2 |
---|---|---|
0 | 1 |
4 |
1 | 2 |
5 |
2 | 3 |
6 |
1 | // unzip |
exercise
1 | // 构造1到100的奇数List |
Seq
**Sequence是一个可枚举的序列,不支持切割操作**
定义Seq
1 | // Sequences can use yield and contain subsequences |
遍历
- Seq.isEmpty
- Seq.length
- Seq.head
- Seq.tail
- Seq.item 1
1 | let seq1 = seq{0..10} |
1 | seq1 |
index | value |
---|---|
0 | 0 |
1 | 1 |
2 | 2 |
3 | 3 |
4 | 4 |
5 | 5 |
6 | 6 |
7 | 7 |
8 | 8 |
9 | 9 |
10 | 10 |
List与Seq
1 | let list1 = [ 1; 2; 3 ] |
Seq与List进行转化
1 | let list1= [0..10] |
Set
**Set中元素不可重复**
1 | let set_1 = [1;2;3] |> set |
API
- set_1.IsSubsetOf(set_2)
- set_1.IsSupersetOf(set_2)
- set_1.IsProperSubsetOf(set_2)
- set_1.IsProperSupersetOf(set_2)
- set0.Count
- set_1 = set_2 // 比较结构相等(值)基础类型
- let set_3 = set_1.Add(0)
- Set.union set_4 set_3
- Set.intersect set_4 set_3
Map
1 | let m=Map.ofList [(1,"cyan")] |
key | value |
---|---|
1 |
cyan |
1 | let m= |
key | value |
---|---|
1 |
cyan |
2 |
gauss |
1 | m.Add(1,"X") |
key | value |
---|---|
1 |
X |
2 |
gauss |
1 | let m2=m.Add(3,"csharp") |
key | value |
---|---|
1 |
cyan |
2 |
gauss |
3 |
csharp |
1 | m2.Keys |
1 | let m = [for i in 1..100 -> (string(i), i*i)] |> Map |
key | value |
---|---|
1 | 1 |
10 | 100 |
100 | 10000 |
11 | 121 |
12 | 144 |
13 | 169 |
14 | 196 |
15 | 225 |
16 | 256 |
17 | 289 |
18 | 324 |
19 | 361 |
2 | 4 |
20 | 400 |
21 | 441 |
22 | 484 |
23 | 529 |
24 | 576 |
25 | 625 |
26 | 676 |
… (more) |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment