F# - 可变列表(Mutable List)

F# - 可变列表(Mutable List) 首页 / F#入门教程 / F# - 可变列表(Mutable List)

List <'T>类表示可以通过索引访问的对象的类型列表,它与数组相似,因为它可以由索引访问,但是,与数组不同,可以调整列表的大小。

创建可变列表

使用 new 关键字并调用列表的构造函数来创建列表。以下示例演示了这一点-

(* Creating a List *)
open System.Collections.Generic

let booksList = new List<string>()
booksList.Add("Gone with the Wind")
booksList.Add("Atlas Shrugged")
booksList.Add("Fountainhead")
booksList.Add("Thornbirds")
booksList.Add("Rebecca")
booksList.Add("Narnia")

booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])

编译并执行程序时,将产生以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-mutable-lists.html

来源:LearnFk无涯教程网

0: Gone with the Wind
1: Atlas Shrugged
2: Fountainhead
3: Thornbirds
4: Rebecca
5: Narnia

可变列表示例

(* Creating a List *)
open System.Collections.Generic

let booksList = new List<string>()
booksList.Add("Gone with the Wind")
booksList.Add("Atlas Shrugged")
booksList.Add("Fountainhead")
booksList.Add("Thornbirds")
booksList.Add("Rebecca")
booksList.Add("Narnia")

printfn"Total %d books" booksList.Count
booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])
booksList.Insert(2, "Roots")

printfn("after inserting at index 2")
printfn"Total %d books" booksList.Count

booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])
booksList.RemoveAt(3)

printfn("after removing from index 3")
printfn"Total %d books" booksList.Count

booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])

编译并执行程序时,将产生以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-mutable-lists.html

来源:LearnFk无涯教程网

Total 6 books
0: Gone with the Wind
1: Atlas Shrugged
2: Fountainhead
3: Thornbirds
4: Rebecca
5: Narnia
after inserting at index 2
Total 7 books
0: Gone with the Wind
1: Atlas Shrugged
2: Roots
3: Fountainhead
4: Thornbirds
5: Rebecca
6: Narnia
after removing from index 3
Total 6 books
0: Gone with the Wind
1: Atlas Shrugged
2: Roots
3: Thornbirds
4: Rebecca
5: Narnia

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

代码精进之路 -〔范学雷〕

Elasticsearch核心技术与实战 -〔阮一鸣〕

Spring Boot与Kubernetes云原生微服务实践 -〔杨波〕

性能工程高手课 -〔庄振运〕

Redis核心技术与实战 -〔蒋德钧〕

分布式数据库30讲 -〔王磊〕

程序员的个人财富课 -〔王喆〕

商业思维案例笔记 -〔曹雄峰〕

AI大模型系统实战 -〔Tyler〕

好记忆不如烂笔头。留下您的足迹吧 :)