MatricesArrays
Las matrices son colecciones mutables de tamaño fijo y de base cero de elementos de datos consecutivos que son del mismo tipo.Arrays are fixed-size, zero-based, mutable collections of consecutive data elements that are all of the same type.
Crear matricesCreate arrays
Puede crear matrices de varias maneras.You can create arrays in several ways. Puede crear una matriz pequeña enumerando valores consecutivos entre [|
y |]
y separados por punto y coma, tal como se muestra en los ejemplos siguientes.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 |]
También puede colocar cada elemento en una línea independiente, en cuyo caso el separador de punto y coma es opcional.You can also put each element on a separate line, in which case the semicolon separator is optional.
let array1 =
[|
1
2
3
|]
El tipo de los elementos de la matriz se deduce de los literales usados y debe ser coherente.The type of the array elements is inferred from the literals used and must be consistent. El código siguiente produce un error porque 1,0 es float y 2 y 3 son enteros.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 |]
También puede utilizar expresiones de secuencia para crear matrices.You can also use sequence expressions to create arrays. A continuación se encuentra un ejemplo que crea una matriz de cuadrados de enteros de 1 a 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 |]
Para crear una matriz en la que todos los elementos se inicializan en cero, use Array.zeroCreate
.To create an array in which all the elements are initialized to zero, use Array.zeroCreate
.
let arrayOfTenZeroes : int array = Array.zeroCreate 10
Elementos de accesoAccess elements
Puede tener acceso a los elementos de la matriz mediante un operador punto ( .
) y corchetes ( [
y ]
).You can access array elements by using a dot operator (.
) and brackets ([
and ]
).
array1.[0]
Los índices de matriz comienzan en 0.Array indexes start at 0.
También puede tener acceso a los elementos de la matriz mediante la notación de segmentación, que permite especificar un subintervalo de la matriz.You can also access array elements by using slice notation, which enables you to specify a subrange of the array. A continuación se muestran ejemplos de notación de segmentación.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..]
Cuando se usa la notación de segmentos, se crea una nueva copia de la matriz.When slice notation is used, a new copy of the array is created.
Tipos de matriz y módulosArray types and modules
El tipo de todas las matrices de F # es el tipo de .NET Framework System.Array .The type of all F# arrays is the .NET Framework type System.Array. Por lo tanto, las matrices de F # admiten toda la funcionalidad disponible en System.Array .Therefore, F# arrays support all the functionality available in System.Array.
El Array
módulo admite operaciones en matrices unidimensionales.The Array
module supports operations on one-dimensional arrays. Los módulos Array2D
, Array3D
y Array4D
contienen funciones que admiten operaciones en matrices de dos, tres y cuatro dimensiones, respectivamente.The modules Array2D
, Array3D
, and Array4D
contain functions that support operations on arrays of two, three, and four dimensions, respectively. Puede crear matrices de rango mayores que cuatro mediante System.Array .You can create arrays of rank greater than four by using System.Array.
Funciones simplesSimple functions
Array.get
Obtiene un elemento.Array.get
gets an element. Array.length
proporciona la longitud de una matriz.Array.length
gives the length of an array. Array.set
establece un elemento en un valor especificado.Array.set
sets an element to a specified value. En el ejemplo de código siguiente se muestra el uso de estas funciones.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)
La salida es la siguiente.The output is as follows.
0 1 2 3 4 5 6 7 8 9
Funciones que crean matricesFunctions that create arrays
Varias funciones crean matrices sin necesidad de una matriz existente.Several functions create arrays without requiring an existing array. Array.empty
crea una nueva matriz que no contiene ningún elemento.Array.empty
creates a new array that does not contain any elements. Array.create
crea una matriz de un tamaño especificado y establece todos los elementos en los valores proporcionados.Array.create
creates an array of a specified size and sets all the elements to provided values. Array.init
crea una matriz, dada una dimensión y una función para generar los elementos.Array.init
creates an array, given a dimension and a function to generate the elements. Array.zeroCreate
crea una matriz en la que todos los elementos se inicializan en el valor cero para el tipo de la matriz.Array.zeroCreate
creates an array in which all the elements are initialized to the zero value for the array's type. En el código siguiente se muestran estas funciones.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
La salida es la siguiente.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
crea una nueva matriz que contiene los elementos que se copian de una matriz existente.Array.copy
creates a new array that contains elements that are copied from an existing array. Tenga en cuenta que la copia es una copia superficial, lo que significa que si el tipo de elemento es un tipo de referencia, solo se copia la referencia, no el objeto subyacente.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. En el siguiente ejemplo código se muestra cómo hacerlo.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
La salida del código anterior es la siguiente:The output of the preceding code is as follows:
[|Test1; Test2; |]
[|; Test2; |]
La cadena Test1
solo aparece en la primera matriz porque la operación de creación de un nuevo elemento sobrescribe la referencia en firstArray
pero no afecta a la referencia original a una cadena vacía que todavía está presente en 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
. La cadena Test2
aparece en ambas matrices porque la Insert
operación en el System.Text.StringBuilder tipo afecta al objeto subyacente System.Text.StringBuilder , al que se hace referencia en ambas matrices.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
genera una nueva matriz a partir de un subintervalo de una matriz.Array.sub
generates a new array from a subrange of an array. Para especificar el subintervalo, proporcione el índice de inicio y la longitud.You specify the subrange by providing the starting index and the length. En el código siguiente se muestra cómo usar 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
La salida muestra que la submatriz comienza en el elemento 5 y contiene 10 elementos.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
crea una nueva matriz combinando dos matrices existentes.Array.append
creates a new array by combining two existing arrays.
En el código siguiente se muestra array. Append.The following code demonstrates Array.append.
printfn "%A" (Array.append [| 1; 2; 3|] [| 4; 5; 6|])
La salida del código anterior es la siguiente.The output of the preceding code is as follows.
[|1; 2; 3; 4; 5; 6|]
Array.choose
selecciona los elementos de una matriz que se van a incluir en una nueva matriz.Array.choose
selects elements of an array to include in a new array. En el siguiente código se muestra Array.choose
.The following code demonstrates Array.choose
. Tenga en cuenta que el tipo de elemento de la matriz no tiene que coincidir con el tipo del valor devuelto en el tipo de opción.Note that the element type of the array does not have to match the type of the value returned in the option type. En este ejemplo, el tipo de elemento es int
y la opción es el resultado de una función polinómica, elem*elem - 1
, como un número de punto flotante.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 |])
La salida del código anterior es la siguiente.The output of the preceding code is as follows.
[|3.0; 15.0; 35.0; 63.0; 99.0|]
Array.collect
ejecuta una función especificada en cada elemento de matriz de una matriz existente y, a continuación, recopila los elementos generados por la función y los combina en una nueva matriz.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. En el siguiente código se muestra Array.collect
.The following code demonstrates Array.collect
.
printfn "%A" (Array.collect (fun elem -> [| 0 .. elem |]) [| 1; 5; 10|])
La salida del código anterior es la siguiente.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
toma una secuencia de matrices y las combina en una sola matriz.Array.concat
takes a sequence of arrays and combines them into a single array. En el siguiente código se muestra Array.concat
.The 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|]
La salida del código anterior es la siguiente.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
toma una función de condición booleana y genera una nueva matriz que contiene solo los elementos de la matriz de entrada para los que la condición es 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. En el siguiente código se muestra Array.filter
.The following code demonstrates Array.filter
.
printfn "%A" (Array.filter (fun elem -> elem % 2 = 0) [| 1 .. 10|])
La salida del código anterior es la siguiente.The output of the preceding code is as follows.
[|2; 4; 6; 8; 10|]
Array.rev
genera una nueva matriz invirtiendo el orden de una matriz existente.Array.rev
generates a new array by reversing the order of an existing array. En el siguiente código se muestra Array.rev
.The following code demonstrates Array.rev
.
let stringReverse (s: string) =
System.String(Array.rev (s.ToCharArray()))
printfn "%A" (stringReverse("!dlrow olleH"))
La salida del código anterior es la siguiente.The output of the preceding code is as follows.
"Hello world!"
Puede combinar fácilmente funciones en el módulo de matriz que transforman matrices mediante el operador de canalización ( |>
), tal como se muestra en el ejemplo siguiente.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"
El resultado esThe output is
[|100; 36; 16; 4|]
Matrices multidimensionalesMultidimensional arrays
Se puede crear una matriz multidimensional, pero no hay ninguna sintaxis para escribir un literal de matriz multidimensional.A multidimensional array can be created, but there is no syntax for writing a multidimensional array literal. Use el operador array2D
para crear una matriz a partir de una secuencia de secuencias de elementos de matriz.Use the operator array2D
to create an array from a sequence of sequences of array elements. Las secuencias pueden ser literales de matriz o lista.The sequences can be array or list literals. Por ejemplo, el código siguiente crea una matriz bidimensional.For example, the following code creates a two-dimensional array.
let my2DArray = array2D [ [ 1; 0]; [0; 1] ]
También puede usar la función Array2D.init
para inicializar matrices de dos dimensiones, y las funciones similares están disponibles para las matrices de tres y cuatro dimensiones.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. Estas funciones toman una función que se utiliza para crear los elementos.These functions take a function that is used to create the elements. Para crear una matriz bidimensional que contenga elementos establecidos en un valor inicial en lugar de especificar una función, use la Array2D.create
función, que también está disponible para matrices de hasta cuatro dimensiones.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. En el ejemplo de código siguiente se muestra primero cómo crear una matriz de matrices que contienen los elementos deseados y, a continuación, Array2D.init
se usa para generar la matriz bidimensional deseada.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])
La sintaxis de indización y segmentación de matrices es compatible con matrices hasta el rango 4.Array indexing and slicing syntax is supported for arrays up to rank 4. Cuando se especifica un índice en varias dimensiones, se usan comas para separar los índices, tal y como se muestra en el ejemplo de código siguiente.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
El tipo de una matriz bidimensional se escribe como <type>[,]
(por ejemplo, int[,]
, double[,]
) y el tipo de una matriz tridimensional se escribe como <type>[,,]
y así sucesivamente para las matrices de dimensiones superiores.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.
Solo hay disponible un subconjunto de las funciones disponibles para las matrices unidimensionales para las matrices multidimensionales.Only a subset of the functions available for one-dimensional arrays is also available for multidimensional arrays.
Segmentación de matrices y matrices multidimensionalesArray slicing and multidimensional arrays
En una matriz bidimensional (matriz), puede extraer una submatriz especificando los intervalos y usando un carácter comodín ( *
) para especificar filas o columnas completas.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]
Puede descomponer una matriz multidimensional en submatrices de la misma dimensión o en una inferior.You can decompose a multidimensional array into subarrays of the same or lower dimension. Por ejemplo, puede obtener un vector de una matriz especificando una sola fila o columna.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]
Puede utilizar esta sintaxis de segmentación para los tipos que implementan los operadores de acceso a elementos y los métodos sobrecargados GetSlice
.You can use this slicing syntax for types that implement the element access operators and overloaded GetSlice
methods. Por ejemplo, el código siguiente crea un tipo de matriz que contiene la matriz 2D de F #, implementa una propiedad Item para proporcionar compatibilidad con la indización de matrices e implementa tres versiones de 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
. Si puede usar este código como plantilla para los tipos de matriz, puede usar todas las operaciones de segmentación que se describen en esta sección.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 $"{submatrix}"
let firstRow = test1.[0,*]
let secondRow = test1.[1,*]
let firstCol = test1.[*,0]
printfn $"{firstCol}"
Funciones booleanas en matricesBoolean functions on arrays
Las funciones Array.exists
y Array.exists2
los elementos de prueba de una o dos matrices, respectivamente.The functions Array.exists
and Array.exists2
test elements in either one or two arrays, respectively. Estas funciones toman una función de prueba y devuelven true
si hay un elemento (o par de elementos para Array.exists2
) que cumple la condición.These functions take a test function and return true
if there is an element (or element pair for Array.exists2
) that satisfies the condition.
En el código siguiente se muestra el uso de Array.exists
y Array.exists2
.The following code demonstrates the use of Array.exists
and Array.exists2
. En estos ejemplos, se crean nuevas funciones aplicando solo uno de los argumentos, en estos casos, el argumento de la función.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|])
La salida del código anterior es la siguiente.The output of the preceding code is as follows.
true
false
false
true
Del mismo modo, la función Array.forall
prueba una matriz para determinar si todos los elementos satisfacen una condición booleana.Similarly, the function Array.forall
tests an array to determine whether every element satisfies a Boolean condition. La variación Array.forall2
hace lo mismo mediante el uso de una función booleana que implica elementos de dos matrices de igual longitud.The variation Array.forall2
does the same thing by using a Boolean function that involves elements of two arrays of equal length. En el código siguiente se muestra el uso de estas funciones.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 |])
La salida de estos ejemplos es la siguiente.The output for these examples is as follows.
false
true
true
false
Buscar matricesSearch arrays
Array.find
toma una función booleana y devuelve el primer elemento para el que devuelve la función true
, o produce una System.Collections.Generic.KeyNotFoundException si no se encuentra ningún elemento que cumpla la condición.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
es como Array.find
, excepto que devuelve el índice del elemento en lugar del propio elemento.Array.findIndex
is like Array.find
, except that it returns the index of the element instead of the element itself.
En el código siguiente Array.find
se usa y Array.findIndex
para buscar un número que sea un cuadrado perfecto y un cubo perfecto.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
La salida es la siguiente.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
es como Array.find
, excepto que su resultado es un tipo de opción y devuelve None
si no se encuentra ningún elemento.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
se debe usar en lugar de Array.find
cuando no se sabe si un elemento coincidente está en la matriz.Array.tryFind
should be used instead of Array.find
when you do not know whether a matching element is in the array. Del mismo modo, Array.tryFindIndex
es como, Array.findIndex
excepto que el tipo de opción es el valor devuelto.Similarly, Array.tryFindIndex
is like Array.findIndex
except that the option type is the return value. Si no se encuentra ningún elemento, la opción es None
.If no element is found, the option is None
.
En el código siguiente se muestra cómo usar Array.tryFind
.The following code demonstrates the use of Array.tryFind
. Este código depende del código anterior.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 |]
La salida es la siguiente.The output is as follows.
Found an element: 1
Found an element: 729
Failed to find a matching element.
Use Array.tryPick
cuando necesite transformar un elemento además de encontrarlo.Use Array.tryPick
when you need to transform an element in addition to finding it. El resultado es el primer elemento para el que la función devuelve el elemento transformado como un valor de opción, o None
si no se encuentra dicho elemento.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.
En el código siguiente se muestra el uso de Array.tryPick
.The following code shows the use of Array.tryPick
. En este caso, en lugar de una expresión lambda, se definen varias funciones auxiliares locales para simplificar el código.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 |]
La salida es la siguiente.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.
Did not find an element that is both a perfect square and a perfect cube.
Realizar cálculos en matricesPerform computations on arrays
La Array.average
función devuelve el promedio de cada elemento de una matriz.The Array.average
function returns the average of each element in an array. Se limita a los tipos de elemento que admiten la división exacta mediante un entero, que incluye los tipos de punto flotante, pero no los tipos enteros.It is limited to element types that support exact division by an integer, which includes floating point types but not integral types. La Array.averageBy
función devuelve el promedio de los resultados de llamar a una función en cada elemento.The Array.averageBy
function returns the average of the results of calling a function on each element. Para una matriz de tipo entero, puede usar Array.averageBy
y hacer que la función convierta cada elemento en un tipo de punto flotante para el cálculo.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.
Use Array.max
o Array.min
para obtener el elemento máximo o mínimo, si el tipo de elemento lo admite.Use Array.max
or Array.min
to get the maximum or minimum element, if the element type supports it. De forma similar, Array.maxBy
y Array.minBy
permiten que una función se ejecute en primer lugar, quizás para realizar la transformación en un tipo que admita la comparación.Similarly, Array.maxBy
and Array.minBy
allow a function to be executed first, perhaps to transform to a type that supports comparison.
Array.sum
agrega los elementos de una matriz y Array.sumBy
llama a una función en cada elemento y agrega los resultados juntos.Array.sum
adds the elements of an array, and Array.sumBy
calls a function on each element and adds the results together.
Para ejecutar una función en cada elemento de una matriz sin almacenar los valores devueltos, use Array.iter
.To execute a function on each element in an array without storing the return values, use Array.iter
. Para una función que implique dos matrices de igual longitud, use Array.iter2
.For a function involving two arrays of equal length, use Array.iter2
. Si también necesita mantener una matriz de los resultados de la función, use Array.map
o Array.map2
, que opera en dos matrices a la vez.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.
Las variaciones Array.iteri
y Array.iteri2
permiten que el índice del elemento esté implicado en el cálculo; lo mismo sucede con Array.mapi
y 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
.
Las funciones,,,, Array.fold
Array.foldBack
Array.reduce
Array.reduceBack
Array.scan
y Array.scanBack
ejecutan algoritmos que implican todos los elementos de una matriz.The functions Array.fold
, Array.foldBack
, Array.reduce
, Array.reduceBack
, Array.scan
, and Array.scanBack
execute algorithms that involve all the elements of an array. Del mismo modo, las variaciones Array.fold2
y Array.foldBack2
realizan cálculos en dos matrices.Similarly, the variations Array.fold2
and Array.foldBack2
perform computations on two arrays.
Estas funciones para realizar cálculos se corresponden con las funciones del mismo nombre en el módulo de lista.These functions for performing computations correspond to the functions of the same name in the List module. Para obtener ejemplos de uso, vea listas.For usage examples, see Lists.
Modificar matricesModify arrays
Array.set
establece un elemento en un valor especificado.Array.set
sets an element to a specified value. Array.fill
establece un intervalo de elementos de una matriz en un valor especificado.Array.fill
sets a range of elements in an array to a specified value. En el código siguiente se proporciona un ejemplo de Array.fill
.The following code provides an example of Array.fill
.
let arrayFill1 = [| 1 .. 25 |]
Array.fill arrayFill1 2 20 0
printfn "%A" arrayFill1
La salida es la siguiente.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|]
Puede usar Array.blit
para copiar una subsección de una matriz en otra matriz.You can use Array.blit
to copy a subsection of one array to another array.
Conversión a y desde otros tiposConvert to and from other types
Array.ofList
crea una matriz a partir de una lista.Array.ofList
creates an array from a list. Array.ofSeq
crea una matriz a partir de una secuencia.Array.ofSeq
creates an array from a sequence. Array.toList
y Array.toSeq
se convierten en estos otros tipos de colección del tipo de matriz.Array.toList
and Array.toSeq
convert to these other collection types from the array type.
Ordenar matricesSort arrays
Use Array.sort
para ordenar una matriz utilizando la función de comparación genérica.Use Array.sort
to sort an array by using the generic comparison function. Utilice Array.sortBy
para especificar una función que genera un valor, al que se hace referencia como clave, para ordenar mediante la función de comparación genérica de la clave.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. Use Array.sortWith
si desea proporcionar una función de comparación personalizada.Use Array.sortWith
if you want to provide a custom comparison function. Array.sort
, Array.sortBy
y Array.sortWith
devuelven la matriz ordenada como una nueva matriz.Array.sort
, Array.sortBy
, and Array.sortWith
all return the sorted array as a new array. Las variaciones Array.sortInPlace
, Array.sortInPlaceBy
y Array.sortInPlaceWith
modifican la matriz existente en lugar de devolver una nueva.The variations Array.sortInPlace
, Array.sortInPlaceBy
, and Array.sortInPlaceWith
modify the existing array instead of returning a new one.
Matrices y tuplasArrays and tuples
Las funciones Array.zip
y Array.unzip
convierten matrices de pares de tupla en tuplas de matrices y viceversa.The functions Array.zip
and Array.unzip
convert arrays of tuple pairs to tuples of arrays and vice versa. Array.zip3
y Array.unzip3
son similares, salvo que funcionan con tuplas de tres elementos o tuplas de tres matrices.Array.zip3
and Array.unzip3
are similar except that they work with tuples of three elements or tuples of three arrays.
Cálculos paralelos en matricesParallel computations on arrays
El módulo Array.Parallel
contiene funciones para realizar cálculos paralelos en matrices.The module Array.Parallel
contains functions for performing parallel computations on arrays. Este módulo no está disponible en las aplicaciones que tienen como destino versiones de .NET Framework anteriores a la versión 4.This module is not available in applications that target versions of the .NET Framework prior to version 4.