📅  最后修改于: 2021-01-01 04:59:03             🧑  作者: Mango
数组是相同类型数据的可变集合。它从0索引开始,到n-1。在此,n是数组的长度。 F#数组支持.Net Framework的System.Array中可用的所有功能。
F#主要提供2种类型的数组
您可以通过在[|之间添加值来创建数组和|]以分号(;)分隔。
let arr = [| 1; 2; 3; 4; 5; |]
您还可以通过使用表达式序列来创建数组。下面的示例创建一个整数数组,其值从1到10。
let arr = [| for i in 1..10->i |]
System.Array中有各种内置方法。它有助于根据需要创建阵列。您可以使用这些方法在F#中创建数组。
Method | Description |
---|---|
Array.empty Ex. let arr = Array.empty |
It creates a new array which does not contain element. |
Array.create Ex. let arr = Array.create 10 2 |
It creates an array of a specified size and sets all the elements to provided value. |
Array.init Ex. let arr = Array.init 10 (fun index -> index) |
It creates an array by using given dimension and a function to generate the elements. |
Array.zeroCreate Ex. let arr = Array.zeroCreate 10 |
It creates an array in which all the elements are initialized to zero. |
let arr = [| 1; 2; 3; 4; 5; |] // Creating and initializing array
for i = 0 to arr.Length-1 do // Traversing of array
printfn "%d" arr.[i]
输出:
1
2
3
4
5
let arr = [| for i in 1..10 -> i |]
for i = 0 to arr.Length-1 do
printfn "%d" arr.[i]
输出:
1
2
3
4
5
6
7
8
9
10
F#Array.create方法创建指定长度的数组,并通过指定的值设置整个数组。稍后,您可以使用Array.set方法后跟索引和值来分配或设置新值。
let arrayName = Array.create 5 0
Array.set arrayName 1 12 // Set element to given index using set function
for i in [0..arrayName.Length-1] do
printfn "%d" arrayName.[i]
输出:
0
12
0
0
0
let printArray(arr:int[]) =
printfn "Printing array elements:"
for i = 0 to arr.Length-1 do
printfn "%d" arr.[i]
let arr1 = [|25; 10; 20; 15; 40; 50; |]
let arr2 = [| 12; 23; 44; 11; 54; |]
printArray arr1
printArray arr2
输出:
Printing array elements:
25
10
20
15
40
50
Printing array elements:
12
23
44
11
54
let printArray (arr:int[]) =
let mutable min = arr.[0]
printf "Minimun element is: "
for i = 1 to arr.Length-1 do
if(min>arr.[i])then
min <- arr.[i]
printfn "%d" min
let arr1 = [|25; 10; 20; 15; 40; 50;|]
let arr2 = [|12; 23; 44; 11; 54;|]
printArray arr1
printArray arr2
输出:
Minimun element is: 10
Minimun element is: 11
let printArray (arr:int[]) =
let mutable max = arr.[0]
printfn "Maximum element is: "
for i = 1 to arr.Length-1 do
if(max
输出:
Maximum element is: 50
Maximum element is: 54
F#允许我们创建多维数组。多维数组也称为数组数组。它可以是2维,3维或更大。
在F#中,可以创建多维数组,但是没有用于编写多维数组的语法。 F#使用array2D运算符从数组元素序列的序列中创建二维数组。序列可以是数组或列表。
在这里,我们使用array2D运算符创建2D数组。
let arr = array2D [ [ 1; 0]; [0; 1] ]
for i = 0 to 1 do
for j = 0 to 1 do
printf "%d " arr.[i,j]
printf "\n"
输出:
1 0
0 1
您可以通过在printf函数使用% A (格式说明符)来print数组矩阵。
let arr = array2D [| [| 1; 0 |]; [| 0; 1 |] |]
printf "%A" arr
输出:
[[1; 0]
[0; 1]]