陣列Arrays

注意

API 參考連結將帶您前往 MSDN。The API reference link will take you to MSDN. docs.microsoft.com API 參考不完整。The docs.microsoft.com API reference is not complete.

陣列是固定大小、以零為基底、可變動的連續資料元素集合,這些專案全都屬於相同的類型。Arrays are fixed-size, zero-based, mutable collections of consecutive data elements that are all of the same type.

建立陣列Creating Arrays

您可以透過數種方式來建立陣列。You can create arrays in several ways. 您可以藉由列出介於和[| |]之間的連續值,並以分號分隔,來建立小型陣列,如下列範例所示。You can create a small array by listing consecutive values between [| and |] and separated by semicolons, as shown in the following examples.

let array1 = [| 1; 2; 3 |]

您也可以將每個元素放在不同的行上,在此情況下,分號分隔符號是選擇性的。You can also put each element on a separate line, in which case the semicolon separator is optional.

let array1 =
    [|
        1
        2
        3
     |]

陣列元素的類型是從使用的常值推斷而來,且必須一致。The type of the array elements is inferred from the literals used and must be consistent. 下列程式碼會造成錯誤,因為1.0 是 float,而2和3是整數。The following code causes an error because 1.0 is a float and 2 and 3 are integers.

// Causes an error.
// let array2 = [| 1.0; 2; 3 |]

您也可以使用順序運算式來建立陣列。You can also use sequence expressions to create arrays. 以下範例會建立從1到10的整數的平方陣列。Following is an example that creates an array of squares of integers from 1 to 10.

let array3 = [| for i in 1 .. 10 -> i * i |]

若要建立陣列,其中所有元素都初始化為零,請使用Array.zeroCreateTo create an array in which all the elements are initialized to zero, use Array.zeroCreate.

let arrayOfTenZeroes : int array = Array.zeroCreate 10

存取元素Accessing Elements

您可以使用點運算子(.)和括弧([])來存取陣列元素。You can access array elements by using a dot operator (.) and brackets ([ and ]).

array1.[0]

陣列索引從0開始。Array indexes start at 0.

您也可以使用配量標記法來存取陣列元素,這可讓您指定陣列的子範圍。You can also access array elements by using slice notation, which enables you to specify a subrange of the array. 配量標記法的範例如下。Examples of slice notation follow.

// Accesses elements from 0 to 2.

array1.[0..2]

// Accesses elements from the beginning of the array to 2.

array1.[..2]

// Accesses elements from 2 to the end of the array.

array1.[2..]

當使用配量標記法時,會建立陣列的新複本。When slice notation is used, a new copy of the array is created.

陣列類型和模組Array Types and Modules

所有F#陣列的類型都是 .NET Framework 類型System.ArrayThe type of all F# arrays is the .NET Framework type System.Array. 因此, F#陣列支援中System.Array提供的所有功能。Therefore, F# arrays support all the functionality available in System.Array.

Library 模組Microsoft.FSharp.Collections.Array支援一維陣列上的作業。The library module Microsoft.FSharp.Collections.Array supports operations on one-dimensional arrays. 模組Array2DArray3D和包含的函式,分別支援兩個、三個和四個維度之陣列的作業。Array4DThe modules Array2D, Array3D, and Array4D contain functions that support operations on arrays of two, three, and four dimensions, respectively. 您可以使用System.Array,建立大於四的次序陣列。You can create arrays of rank greater than four by using System.Array.

簡單函式Simple Functions

Array.get取得元素。Array.get gets an element. Array.length提供陣列的長度。Array.length gives the length of an array. Array.set將元素設定為指定的值。Array.set sets an element to a specified value. 下列程式碼範例說明如何使用這些函數。The following code example illustrates the use of these functions.

let array1 = Array.create 10 ""
for i in 0 .. array1.Length - 1 do
    Array.set array1 i (i.ToString())
for i in 0 .. array1.Length - 1 do
    printf "%s " (Array.get array1 i)

輸出如下。The output is as follows.

0 1 2 3 4 5 6 7 8 9

建立陣列的函式Functions That Create Arrays

有數個函式會建立陣列,而不需要現有的陣列。Several functions create arrays without requiring an existing array. Array.empty建立不包含任何元素的新陣列。Array.empty creates a new array that does not contain any elements. Array.create建立指定大小的陣列,並將所有元素設定為提供的值。Array.create creates an array of a specified size and sets all the elements to provided values. Array.init建立陣列,並指定要產生元素的維度和函式。Array.init creates an array, given a dimension and a function to generate the elements. Array.zeroCreate建立陣列,其中所有的元素都會初始化為數組類型的零值。Array.zeroCreate creates an array in which all the elements are initialized to the zero value for the array's type. 下列程式碼會示範這些函數。The following code demonstrates these functions.

let myEmptyArray = Array.empty
printfn "Length of empty array: %d" myEmptyArray.Length



printfn "Array of floats set to 5.0: %A" (Array.create 10 5.0)


printfn "Array of squares: %A" (Array.init 10 (fun index -> index * index))

let (myZeroArray : float array) = Array.zeroCreate 10

輸出如下。The output is as follows.

Length of empty array: 0
Area of floats set to 5.0: [|5.0; 5.0; 5.0; 5.0; 5.0; 5.0; 5.0; 5.0; 5.0; 5.0|]
Array of squares: [|0; 1; 4; 9; 16; 25; 36; 49; 64; 81|]

Array.copy建立新的陣列,其中包含從現有陣列複製的元素。Array.copy creates a new array that contains elements that are copied from an existing array. 請注意,複製是淺層複製,這表示如果元素類型是參考型別,則只會複製參考,而不會複製基礎物件。Note that the copy is a shallow copy, which means that if the element type is a reference type, only the reference is copied, not the underlying object. 下列程式碼範例會說明這點。The following code example illustrates this.

open System.Text

let firstArray : StringBuilder array = Array.init 3 (fun index -> new StringBuilder(""))
let secondArray = Array.copy firstArray
// Reset an element of the first array to a new value.
firstArray.[0] <- new StringBuilder("Test1")
// Change an element of the first array.
firstArray.[1].Insert(0, "Test2") |> ignore
printfn "%A" firstArray
printfn "%A" secondArray

上述程式碼的輸出如下所示:The output of the preceding code is as follows:

[|Test1; Test2; |]
[|; Test2; |]

此字串Test1只會出現在第一個陣列中,因為建立新專案的作業會覆寫firstArray中的參考,但不會影響仍然存在於中secondArray之空字串的原始參考。The string Test1 appears only in the first array because the operation of creating a new element overwrites the reference in firstArray but does not affect the original reference to an empty string that is still present in secondArray. 此字串Test2會出現在這兩個Insert陣列中, System.Text.StringBuilder因為類型的作業System.Text.StringBuilder會影響在這兩個數組中所參考的基礎物件。The string Test2 appears in both arrays because the Insert operation on the System.Text.StringBuilder type affects the underlying System.Text.StringBuilder object, which is referenced in both arrays.

Array.sub從陣列的子範圍產生新的陣列。Array.sub generates a new array from a subrange of an array. 您可以藉由提供起始索引和長度來指定子範圍。You specify the subrange by providing the starting index and the length. 下列程式碼示範 Array.sub 的用法。The following code demonstrates the use of Array.sub.

let a1 = [| 0 .. 99 |]
let a2 = Array.sub a1 5 10
printfn "%A" a2

輸出顯示子陣列從專案5開始,且包含10個元素。The output shows that the subarray starts at element 5 and contains 10 elements.

[|5; 6; 7; 8; 9; 10; 11; 12; 13; 14|]

Array.append結合兩個現有的陣列,以建立新的陣列。Array.append creates a new array by combining two existing arrays.

下列程式碼示範陣列. appendThe following code demonstrates Array.append.

printfn "%A" (Array.append [| 1; 2; 3|] [| 4; 5; 6|])

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

[|1; 2; 3; 4; 5; 6|]

Array.choose選取要包含在新陣列中之陣列的元素。Array.choose selects elements of an array to include in a new array. 下列程式碼示範Array.chooseThe following code demonstrates Array.choose. 請注意,陣列的元素類型不一定要符合選項類型中所傳回值的類型。Note that the element type of the array does not have to match the type of the value returned in the option type. 在此範例中,專案類型為int ,而選項是多項式elem*elem - 1函式的結果(做為浮點數)。In this example, the element type is int and the option is the result of a polynomial function, elem*elem - 1, as a floating point number.

printfn "%A" (Array.choose (fun elem -> if elem % 2 = 0 then
                                            Some(float (elem*elem - 1))
                                        else
                                            None) [| 1 .. 10 |])

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

[|3.0; 15.0; 35.0; 63.0; 99.0|]

Array.collect在現有陣列的每個陣列元素上執行指定的函式,然後收集函數所產生的專案,並將它們結合到新的陣列中。Array.collect runs a specified function on each array element of an existing array and then collects the elements generated by the function and combines them into a new array. 下列程式碼示範Array.collectThe following code demonstrates Array.collect.

printfn "%A" (Array.collect (fun elem -> [| 0 .. elem |]) [| 1; 5; 10|])

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

[|0; 1; 0; 1; 2; 3; 4; 5; 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]

Array.concat採用一連串的陣列,並將它們結合成單一陣列。Array.concat takes a sequence of arrays and combines them into a single array. 下列程式碼示範Array.concatThe following code demonstrates Array.concat.

Array.concat [ [|0..3|] ; [|4|] ]
//output [|0; 1; 2; 3; 4|]

Array.concat [| [|0..3|] ; [|4|] |]
//output [|0; 1; 2; 3; 4|]

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

[|(1, 1, 1); (1, 2, 2); (1, 3, 3); (2, 1, 2); (2, 2, 4); (2, 3, 6); (3, 1, 3);
(3, 2, 6); (3, 3, 9)|]

Array.filter採用布林條件函式,並產生新的陣列,其中只包含來自輸入陣列的條件為 true 的元素。Array.filter takes a Boolean condition function and generates a new array that contains only those elements from the input array for which the condition is true. 下列程式碼示範Array.filterThe following code demonstrates Array.filter.

printfn "%A" (Array.filter (fun elem -> elem % 2 = 0) [| 1 .. 10|])

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

[|2; 4; 6; 8; 10|]

Array.rev藉由反轉現有陣列的順序,產生新的陣列。Array.rev generates a new array by reversing the order of an existing array. 下列程式碼示範Array.revThe following code demonstrates Array.rev.

let stringReverse (s: string) =
    System.String(Array.rev (s.ToCharArray()))

printfn "%A" (stringReverse("!dlrow olleH"))

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

"Hello world!"

您可以使用管線運算子(|>)輕鬆地結合陣列模組中的函式,以轉換陣列,如下列範例所示。You can easily combine functions in the array module that transform arrays by using the pipeline operator (|>), as shown in the following example.

[| 1 .. 10 |]
|> Array.filter (fun elem -> elem % 2 = 0)
|> Array.choose (fun elem -> if (elem <> 8) then Some(elem*elem) else None)
|> Array.rev
|> printfn "%A"

輸出為The output is

[|100; 36; 16; 4|]

多維陣列Multidimensional Arrays

多維陣列可以建立,但是沒有寫入多維陣列常值的語法。A multidimensional array can be created, but there is no syntax for writing a multidimensional array literal. 使用運算子array2D ,從陣列元素的序列順序建立陣列。Use the operator array2D to create an array from a sequence of sequences of array elements. 序列可以是陣列或清單常值。The sequences can be array or list literals. 例如,下列程式碼會建立二維陣列。For example, the following code creates a two-dimensional array.

let my2DArray = array2D [ [ 1; 0]; [0; 1] ]

您也可以使用Array2D.init函式來初始化兩個維度的陣列,而類似的函數適用于三和四個維度的陣列。You can also use the function Array2D.init to initialize arrays of two dimensions, and similar functions are available for arrays of three and four dimensions. 這些函式會採用用來建立元素的函式。These functions take a function that is used to create the elements. 若要建立二維陣列,其中包含設定為初始值的專案,而不是指定函式,請使用Array2D.create函式,此函數也適用于最多四個維度的陣列。To create a two-dimensional array that contains elements set to an initial value instead of specifying a function, use the Array2D.create function, which is also available for arrays up to four dimensions. 下列程式碼範例會先示範如何建立陣列陣列,其中包含所需的元素,然後使用Array2D.init來產生所需的二維陣列。The following code example first shows how to create an array of arrays that contain the desired elements, and then uses Array2D.init to generate the desired two-dimensional array.

let arrayOfArrays = [| [| 1.0; 0.0 |]; [|0.0; 1.0 |] |]
let twoDimensionalArray = Array2D.init 2 2 (fun i j -> arrayOfArrays.[i].[j])

陣列的索引和配量語法支援最高至等級4的陣列。Array indexing and slicing syntax is supported for arrays up to rank 4. 當您指定多個維度中的索引時,您可以使用逗號來分隔索引,如下列程式碼範例所示。When you specify an index in multiple dimensions, you use commas to separate the indexes, as illustrated in the following code example.

twoDimensionalArray.[0, 1] <- 1.0

二維陣列的類型會寫出<type>[,]為( int[,]例如,, double[,]),而三維陣列的類型則會寫入為<type>[,,],而對於較高維度的陣列則為。The type of a two-dimensional array is written out as <type>[,] (for example, int[,], double[,]), and the type of a three-dimensional array is written as <type>[,,], and so on for arrays of higher dimensions.

只有一維陣列可用的函數子集也適用于多維陣列。Only a subset of the functions available for one-dimensional arrays is also available for multidimensional arrays. 如需詳細資訊, Collections.Array ModuleCollections.Array2D Module參閱Collections.Array3D Module、、 Collections.Array4D Module和。For more information, see Collections.Array Module, Collections.Array2D Module, Collections.Array3D Module, and Collections.Array4D Module.

陣列切割和多維陣列Array Slicing and Multidimensional Arrays

在二維陣列(矩陣)中,您可以藉由指定範圍並使用萬用字元(*)字元來指定完整的資料列或資料行,來將子矩陣解壓縮。In a two-dimensional array (a matrix), you can extract a sub-matrix by specifying ranges and using a wildcard (*) character to specify whole rows or columns.

// Get rows 1 to N from an NxM matrix (returns a matrix):
matrix.[1.., *]

// Get rows 1 to 3 from a matrix (returns a matrix):
matrix.[1..3, *]

// Get columns 1 to 3 from a matrix (returns a matrix):
matrix.[*, 1..3]

// Get a 3x3 submatrix:
matrix.[1..3, 1..3]

從F# 3.1,您可以將多維陣列分解成相同或較低維度的 subarrays。As of F# 3.1, you can decompose a multidimensional array into subarrays of the same or lower dimension. 例如,您可以藉由指定單一資料列或資料行,從矩陣取得向量。For example, you can obtain a vector from a matrix by specifying a single row or column.

// Get row 3 from a matrix as a vector:
matrix.[3, *]

// Get column 3 from a matrix as a vector:
matrix.[*, 3]

您可以針對實作為元素存取運算子和GetSlice多載方法的類型使用此切割語法。You can use this slicing syntax for types that implement the element access operators and overloaded GetSlice methods. 例如,下列程式碼會建立包裝F# 2d 陣列的矩陣類型、執行專案屬性以提供陣列索引編制的支援,以及執行的GetSlice三個版本。For example, the following code creates a Matrix type that wraps the F# 2D array, implements an Item property to provide support for array indexing, and implements three versions of GetSlice. 如果您可以使用此程式碼當做矩陣類型的範本,則可以使用本節所述的所有切割作業。If you can use this code as a template for your matrix types, you can use all the slicing operations that this section describes.

type Matrix<'T>(N: int, M: int) =
    let internalArray = Array2D.zeroCreate<'T> N M

    member this.Item
        with get(a: int, b: int) = internalArray.[a, b]
        and set(a: int, b: int) (value:'T) = internalArray.[a, b] <- value

    member this.GetSlice(rowStart: int option, rowFinish : int option, colStart: int option, colFinish : int option) =
        let rowStart =
            match rowStart with
            | Some(v) -> v
            | None -> 0
        let rowFinish =
            match rowFinish with
            | Some(v) -> v
            | None -> internalArray.GetLength(0) - 1
        let colStart =
            match colStart with
            | Some(v) -> v
            | None -> 0
        let colFinish =
            match colFinish with
            | Some(v) -> v
            | None -> internalArray.GetLength(1) - 1
        internalArray.[rowStart..rowFinish, colStart..colFinish]

    member this.GetSlice(row: int, colStart: int option, colFinish: int option) =
        let colStart =
            match colStart with
            | Some(v) -> v
            | None -> 0
        let colFinish =
            match colFinish with
            | Some(v) -> v
            | None -> internalArray.GetLength(1) - 1
        internalArray.[row, colStart..colFinish]

    member this.GetSlice(rowStart: int option, rowFinish: int option, col: int) =
        let rowStart =
            match rowStart with
            | Some(v) -> v
            | None -> 0
        let rowFinish =
            match rowFinish with
            | Some(v) -> v
            | None -> internalArray.GetLength(0) - 1
        internalArray.[rowStart..rowFinish, col]

module test =
    let generateTestMatrix x y =
        let matrix = new Matrix<float>(3, 3)
        for i in 0..2 do
            for j in 0..2 do
                matrix.[i, j] <- float(i) * x - float(j) * y
        matrix

    let test1 = generateTestMatrix 2.3 1.1
    let submatrix = test1.[0..1, 0..1]
    printfn "%A" submatrix

    let firstRow = test1.[0,*]
    let secondRow = test1.[1,*]
    let firstCol = test1.[*,0]
    printfn "%A" firstCol

陣列上的布耳函數Boolean Functions on Arrays

一或兩Array.exists2個數組中的函式和測試專案分別為。Array.existsThe functions Array.exists and Array.exists2 test elements in either one or two arrays, respectively. 這些函式會採用測試函式true ,並在有符合條件的元素(或Array.exists2專案組)時傳回。These functions take a test function and return true if there is an element (or element pair for Array.exists2) that satisfies the condition.

下列程式碼示範Array.existsArray.exists2的用法。The following code demonstrates the use of Array.exists and Array.exists2. 在這些範例中,會藉由只套用其中一個引數(在這些情況下為函數引數)來建立新的函式。In these examples, new functions are created by applying only one of the arguments, in these cases, the function argument.

let allNegative = Array.exists (fun elem -> abs (elem) = elem) >> not
printfn "%A" (allNegative [| -1; -2; -3 |])
printfn "%A" (allNegative [| -10; -1; 5 |])
printfn "%A" (allNegative [| 0 |])


let haveEqualElement = Array.exists2 (fun elem1 elem2 -> elem1 = elem2)
printfn "%A" (haveEqualElement [| 1; 2; 3 |] [| 3; 2; 1|])

上述程式碼的輸出如下所示。The output of the preceding code is as follows.

true
false
false
true

同樣地, Array.forall函式會測試陣列,以判斷每個元素是否符合布林條件。Similarly, the function Array.forall tests an array to determine whether every element satisfies a Boolean condition. 此變化Array.forall2會使用包含兩個相等長度陣列之元素的布林函式,來執行相同的工作。The variation Array.forall2 does the same thing by using a Boolean function that involves elements of two arrays of equal length. 下列程式碼說明這些函式的用法。The following code illustrates the use of these functions.

let allPositive = Array.forall (fun elem -> elem > 0)
printfn "%A" (allPositive [| 0; 1; 2; 3 |])
printfn "%A" (allPositive [| 1; 2; 3 |])


let allEqual = Array.forall2 (fun elem1 elem2 -> elem1 = elem2)
printfn "%A" (allEqual [| 1; 2 |] [| 1; 2 |])
printfn "%A" (allEqual [| 1; 2 |] [| 2; 1 |])

這些範例的輸出如下所示。The output for these examples is as follows.

false
true
true
false

搜尋陣列Searching Arrays

Array.find採用布耳函數,並傳回函式傳回的第一個true專案, System.Collections.Generic.KeyNotFoundException如果找不到符合條件的專案,則會引發。Array.find takes a Boolean function and returns the first element for which the function returns true, or raises a System.Collections.Generic.KeyNotFoundException if no element that satisfies the condition is found. Array.findIndex類似Array.find,但它會傳回專案的索引,而不是元素本身。Array.findIndex is like Array.find, except that it returns the index of the element instead of the element itself.

下列程式碼會Array.find使用Array.findIndex和來尋找同時為完美方形和完美 cube 的數位。The following code uses Array.find and Array.findIndex to locate a number that is both a perfect square and perfect cube.

let arrayA = [| 2 .. 100 |]
let delta = 1.0e-10
let isPerfectSquare (x:int) =
    let y = sqrt (float x)
    abs(y - round y) < delta
let isPerfectCube (x:int) =
    let y = System.Math.Pow(float x, 1.0/3.0)
    abs(y - round y) < delta
let element = Array.find (fun elem -> isPerfectSquare elem && isPerfectCube elem) arrayA
let index = Array.findIndex (fun elem -> isPerfectSquare elem && isPerfectCube elem) arrayA
printfn "The first element that is both a square and a cube is %d and its index is %d." element index

輸出如下。The output is as follows.

The first element that is both a square and a cube is 64 and its index is 62.

Array.tryFind類似于Array.find,但它的結果是選項類型, None如果找不到任何元素,則會傳回。Array.tryFind is like Array.find, except that its result is an option type, and it returns None if no element is found. Array.tryFind``Array.find當您不知道相符的元素是否在陣列中時,應該使用而不是。Array.tryFind should be used instead of Array.find when you do not know whether a matching element is in the array. 同樣地Array.tryFindIndex ,類似Array.findIndex于選項類型為傳回值的例外。Similarly, Array.tryFindIndex is like Array.findIndex except that the option type is the return value. 如果找不到任何元素,則選項None為。If no element is found, the option is None.

下列程式碼示範 Array.tryFind 的用法。The following code demonstrates the use of Array.tryFind. 此程式碼視先前的程式碼而定。This code depends on the previous code.

let delta = 1.0e-10
let isPerfectSquare (x:int) =
    let y = sqrt (float x)
    abs(y - round y) < delta
let isPerfectCube (x:int) =
    let y = System.Math.Pow(float x, 1.0/3.0)
    abs(y - round y) < delta
let lookForCubeAndSquare array1 =
    let result = Array.tryFind (fun elem -> isPerfectSquare elem && isPerfectCube elem) array1
    match result with
    | Some x -> printfn "Found an element: %d" x
    | None -> printfn "Failed to find a matching element."

lookForCubeAndSquare [| 1 .. 10 |]
lookForCubeAndSquare [| 100 .. 1000 |]
lookForCubeAndSquare [| 2 .. 50 |]

輸出如下。The output is as follows.

Found an element: 1
Found an element: 729

Array.tryPick您需要轉換專案,以及找出元素時,請使用。Use Array.tryPick when you need to transform an element in addition to finding it. 結果是第一個專案,函式會將轉換的元素當做選項值傳回, None如果找不到這類元素,則為。The result is the first element for which the function returns the transformed element as an option value, or None if no such element is found.

下列程式碼示範 Array.tryPick 的用法。The following code shows the use of Array.tryPick. 在此情況下,會定義數個本機 helper 函式來簡化程式碼,而不是 lambda 運算式。In this case, instead of a lambda expression, several local helper functions are defined to simplify the code.

let findPerfectSquareAndCube array1 =
    let delta = 1.0e-10
    let isPerfectSquare (x:int) =
        let y = sqrt (float x)
        abs(y - round y) < delta
    let isPerfectCube (x:int) =
        let y = System.Math.Pow(float x, 1.0/3.0)
        abs(y - round y) < delta
    // intFunction : (float -> float) -> int -> int
    // Allows the use of a floating point function with integers.
    let intFunction function1 number = int (round (function1 (float number)))
    let cubeRoot x = System.Math.Pow(x, 1.0/3.0)
    // testElement: int -> (int * int * int) option
    // Test an element to see whether it is a perfect square and a perfect
    // cube, and, if so, return the element, square root, and cube root
    // as an option value. Otherwise, return None.
    let testElement elem =
        if isPerfectSquare elem && isPerfectCube elem then
            Some(elem, intFunction sqrt elem, intFunction cubeRoot elem)
        else None
    match Array.tryPick testElement array1 with
    | Some (n, sqrt, cuberoot) -> printfn "Found an element %d with square root %d and cube root %d." n sqrt cuberoot
    | None -> printfn "Did not find an element that is both a perfect square and a perfect cube."

findPerfectSquareAndCube [| 1 .. 10 |]
findPerfectSquareAndCube [| 2 .. 100 |]
findPerfectSquareAndCube [| 100 .. 1000 |]
findPerfectSquareAndCube [| 1000 .. 10000 |]
findPerfectSquareAndCube [| 2 .. 50 |]

輸出如下。The output is as follows.

Found an element 1 with square root 1 and cube root 1.
Found an element 64 with square root 8 and cube root 4.
Found an element 729 with square root 27 and cube root 9.
Found an element 4096 with square root 64 and cube root 16.

在陣列上執行計算Performing Computations on Arrays

Array.average函式會傳回陣列中每個元素的平均值。The Array.average function returns the average of each element in an array. 它受限於支援精確除以整數的元素類型,其中包括浮點類型,而不是整數類型。It is limited to element types that support exact division by an integer, which includes floating point types but not integral types. Array.averageBy函式會傳回每個元素上呼叫函式的結果平均值。The Array.averageBy function returns the average of the results of calling a function on each element. 針對整數類型的陣列,您可以使用Array.averageBy ,並讓函式將每個專案轉換成浮點類型以進行計算。For an array of integral type, you can use Array.averageBy and have the function convert each element to a floating point type for the computation.

如果Array.max元素Array.min類型支援,請使用或來取得最大或最小專案。Use Array.max or Array.min to get the maximum or minimum element, if the element type supports it. 同樣地Array.maxByArray.minBy和允許先執行函式,可能會轉換成支援比較的類型。Similarly, Array.maxBy and Array.minBy allow a function to be executed first, perhaps to transform to a type that supports comparison.

Array.sum加入陣列的元素,並Array.sumBy在每個專案上呼叫函式,並將結果加在一起。Array.sum adds the elements of an array, and Array.sumBy calls a function on each element and adds the results together.

若要在陣列中的每個元素上執行函式,而不儲存Array.iter傳回值,請使用。To execute a function on each element in an array without storing the return values, use Array.iter. 對於涉及兩個相等長度陣列的函數,請Array.iter2使用。For a function involving two arrays of equal length, use Array.iter2. 如果您也需要保留函數結果的陣列,請使用Array.mapArray.map2,這會在兩個數組上一次操作。If you also need to keep an array of the results of the function, use Array.map or Array.map2, which operates on two arrays at a time.

變數的Array.iteri變化Array.iteri2和允許專案的索引會包含在計算中, Array.mapi而和Array.mapi2則相同。The variations Array.iteri and Array.iteri2 allow the index of the element to be involved in the computation; the same is true for Array.mapi and Array.mapi2.

Array.foldBack函式Array.reduce、、Array.scanBack 、和包含陣列所有元素的執行演算法。 Array.reduceBack Array.fold Array.scanThe functions Array.fold, Array.foldBack, Array.reduce, Array.reduceBack, Array.scan, and Array.scanBack execute algorithms that involve all the elements of an array. 同樣地,變數Array.fold2Array.foldBack2會在兩個數組上執行計算。Similarly, the variations Array.fold2 and Array.foldBack2 perform computations on two arrays.

這些用來執行計算的函式會對應至清單模組中相同名稱的函式。These functions for performing computations correspond to the functions of the same name in the List module. 如需使用範例,請參閱清單For usage examples, see Lists.

修改陣列Modifying Arrays

Array.set將元素設定為指定的值。Array.set sets an element to a specified value. Array.fill將陣列中的元素範圍設定為指定的值。Array.fill sets a range of elements in an array to a specified value. 下列程式碼提供的範例Array.fillThe following code provides an example of Array.fill.

let arrayFill1 = [| 1 .. 25 |]
Array.fill arrayFill1 2 20 0
printfn "%A" arrayFill1

輸出如下。The output is as follows.

[|1; 2; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 23; 24; 25|]

您可以使用Array.blit ,將一個陣列的子區段複製到另一個陣列。You can use Array.blit to copy a subsection of one array to another array.

來回轉換其他類型Converting to and from Other Types

Array.ofList從清單建立陣列。Array.ofList creates an array from a list. Array.ofSeq從序列建立陣列。Array.ofSeq creates an array from a sequence. Array.toListArray.toSeq會從陣列類型轉換成這些其他集合類型。Array.toList and Array.toSeq convert to these other collection types from the array type.

排序陣列Sorting Arrays

使用Array.sort來排序陣列,方法是使用泛型比較函數。Use Array.sort to sort an array by using the generic comparison function. 使用Array.sortBy來指定產生值(稱為索引)的函式,以使用索引鍵上的泛型比較函數進行排序。Use Array.sortBy to specify a function that generates a value, referred to as a key, to sort by using the generic comparison function on the key. 如果Array.sortWith您想要提供自訂比較函數,請使用。Use Array.sortWith if you want to provide a custom comparison function. Array.sortArray.sortByArray.sortWith全都會以新陣列的形式傳回已排序的陣列。Array.sort, Array.sortBy, and Array.sortWith all return the sorted array as a new array. 變體Array.sortInPlaceArray.sortInPlaceByArray.sortInPlaceWith會修改現有的陣列,而不是傳回新的陣列。The variations Array.sortInPlace, Array.sortInPlaceBy, and Array.sortInPlaceWith modify the existing array instead of returning a new one.

陣列和元組Arrays and Tuples

函式會將元組配對的陣列轉換成陣列的元組,反之亦然。Array.unzip Array.zipThe functions Array.zip and Array.unzip convert arrays of tuple pairs to tuples of arrays and vice versa. Array.zip3Array.unzip3很相似,不同之處在于它們會與三個數組的三個元素或元組的元組搭配使用。Array.zip3 and Array.unzip3 are similar except that they work with tuples of three elements or tuples of three arrays.

陣列上的平行計算Parallel Computations on Arrays

模組Array.Parallel包含在陣列上執行平行計算的函數。The module Array.Parallel contains functions for performing parallel computations on arrays. 在版本4之前以 .NET Framework 版本為目標的應用程式中,無法使用此模組。This module is not available in applications that target versions of the .NET Framework prior to version 4.

另請參閱See also