Compartilhar via


Função Array.tryPick<'T,'U> (F#)

Aplica a função determinada para sucessivos elementos, retornando o primeiro resultado onde a função retorna Some. Se a função não retorna Some para qualquer elemento, então None será retornado.

Namespace/Module Path: Microsoft.FSharp.Collections.Array

Assembly: FSharp.Core (em FSharp.Core.dll)

// Signature:
Array.tryPick : ('T -> 'U option) -> 'T [] -> 'U option

// Usage:
Array.tryPick chooser array

Parâmetros

  • chooser
    Tipo: 'T -> 'U option

    A função para transformar os elementos da matriz opções em.

  • array
    Tipo: 'T[]

    A matriz de entrada.

Valor de retorno

O primeiro elemento transformado que tem um valor de opção de Some, ou None se a função não retorna Some para qualquer elemento.

Comentários

Essa função é chamada TryPick em assemblies compilados. Se você está acessando a função de um idioma diferente F#, ou com a reflexão, use este nome.

Exemplo

O exemplo a seguir demonstra o uso de Array.tryPick tentar localizar um elemento que satisfaz uma condição, e também retorna alguns dados adicionais sobre o elemento, caso na raiz quadrada e a raiz do cubo.

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 |]
  
  
  
  
  

Plataformas

O windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

Informações de Versão

Versões da biblioteca principal de F#

Suportado em: 2,0, 4,0, portáteis

Consulte também

Referência

Módulo Collections.Array (F#)

Namespace Microsoft.FSharp.Collections (F#)