个性化阅读
专注于IT技术分析

F#List用法

本文概述

List是相同类型元素的不可变集合。它不允许重复的元素。它保持元素的顺序。


F#创建和初始化列表示例

有多种创建列表的方法。一些在下面描述。

let list = [1;2;3;4;5]            // You can create and initialize list at the same time

let list = [
     1
     2
     3
     4
     5
 ]		// Here, semicolon is optional, and you can pass each new element to new line

let list = [1 .. 5]    // You are allowed to initialize list by passing starting and last elements only.

F#List范例

let list = [1;2;3;4;5;6;7;8;9]
for i  in list do
 printfn "%d" i

输出:

1
2
3
4
5
6
7
8
9

F#将新元素添加到列表中

你可以使用::(cons)运算符将新元素添加到列表中。让我们来看一个例子。

let list = [1;2;3;4;5]
for i in list do
 printf "%d " i 
printfn "\n" 
let list2 = 0::list                // Adding new element here
for i in list2 do 
  printf "%d " i

输出:

1 2 3 4 5
0 1 2 3 4 5

两列表示例的F#串联

你可以使用@运算符连接两个具有相同类型的列表。让我们来看一个例子。

let list1  = [1; 2; 3; 4; 5]
let list2  = [6; 7; 8; 9; 10]
let list3 = list1@list2			 // Here, @ operator used for concatenation
for i in list3 do
 printfn "%d " i

输出:

1
2
3
4
5
6
7
8
9
10

F#List属性

F#列表提供了重要的属性。它也有助于优化和维护代码。

属性 描述
Head 它返回列表的第一个元素。
Empty 它返回空列表。
IsEmpty 如果列表为空, 则返回true
Length 它返回元素数。
Tail 它返回不包括第一个元素的列表。

F#列表属性示例

let list = [ 1; 2; 3; 4; 5 ]

printfn "Is list Empty: %b" (list.IsEmpty)
printfn "Length of list is %d" (list.Length)
printfn "Head element of list is %d" (list.Head)
printfn "Tail element of Head in the list is %d" (list.Tail.Head)
printfn "Tail element of tail of head of list %d" (list.Tail.Tail.Head)
printfn "Element at 1 index is %d" (list.Item(1))

输出:

Is list Empty: false
Length of list is 5
Head element of list is 1
Tail element of Head in the list is 2
Tail element of tail of head of list 3
Element at 1 index is 2

在F#中, list提供了用于对元素进行排序和搜索的内置函数。


F#列表排序示例

let list = List.sort[23; 54; 12; 7; 43; 89; 0; 10; 90]
for i in list do
 printfn "%d" i

输出:

0
7
10
12
23
43
54
89
90

F#列表搜索示例

List提供List.find()函数以在列表中查找元素。它返回第一个匹配的元素, 如果找不到该元素, 则抛出System.Collections.Generic.KeyNotFoundException异常。

let isFound number elem = elem = number 
let result = List.find (isFound 10) [ 1 .. 100 ]
printfn "%d " result

输出:

10

列表中的F#压缩和解压缩功能

Zip函数将两个单值列表组合为一个元组列表。解压缩功能将一个元组列表分成两个单值列表。


F#列表压缩示例

.
let zipExample list1 list2 =
 printf "Given Lists: \n List1: %A \n List2: %A" list1 list2
 List.zip list1 list2

let zippedlist = zipExample [1..10][1..10]
printf "\nResult(Zipped List):\n %A" zippedlist

输出:

Given Lists:
 List1: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
 List2: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
Result(Zipped List):
 [(1, 1); (2, 2); (3, 3); (4, 4); (5, 5); (6, 6); (7, 7); (8, 8); (9, 9);
 (10, 10)]

F#列表解压缩示例

let unzipExample zippedList =
 List.unzip zippedList

let unzippedList = unzipExample [(1, 2); (3, 4); (5, 6)]
printf "\nFirst List: %A \nSecond List: %A" (fst unzippedList)(snd unzippedList)

输出:

First List: [1; 3; 5]
Second List: [2; 4; 6]
赞(0)
未经允许不得转载:srcmini » F#List用法

评论 抢沙发

评论前必须登录!