¿Qué es F#What is F#

F#es un lenguaje de programación funcional que resulta muy fácil escribir código correcto y fácil de mantener.F# is a functional programming language that makes it easy to write correct and maintainable code.

F#programación principalmente implica la definición de tipos y funciones que son de tipo deduce y generalizadas automáticamente.F# programming primarily involves defining types and functions that are type-inferred and generalized automatically. Esto permite que el enfoque a permanecer en el dominio del problema y manipular los datos, en lugar de los detalles de la programación.This allows your focus to remain on the problem domain and manipulating its data, rather than the details of programming.

open System // Gets access to functionality in System namespace.

// Defines a function that takes a name and produces a greeting.
let getGreeting name =
    sprintf "Hello, %s! Isn't F# great?" name

[<EntryPoint>]
let main args =
    // Defines a list of names
    let names = [ "Don"; "Julia"; "Xi" ]

    // Prints a greeting for each name!
    names
    |> List.map getGreeting
    |> List.iter (fun greeting -> printfn "%s" greeting)

    0

F#tiene numerosas características, incluidos:F# has numerous features, including:

  • Sintaxis ligeraLightweight syntax
  • Inmutables de manera predeterminadaImmutable by default
  • Generalización automática y la inferencia de tiposType inference and automatic generalization
  • Funciones de primera claseFirst-class functions
  • Tipos de datos eficacesPowerful data types
  • Detección de patronesPattern matching
  • Programación asincrónicaAsync programming

Un conjunto completo de características se documentan en el F# referencia del lenguaje.A full set of features are documented in the F# language reference.

Tipos de datos enriquecidoRich data types

Tipos de datos como registros y uniones discriminadas le permite representar datos complejos y dominios.Data types such as Records and Discriminated Unions let you represent complex data and domains.

// Group data with Records
type SuccessfulWithdrawal = {
    Amount: decimal
    Balance: decimal
}

type FailedWithdrawal = {
    Amount: decimal
    Balance: decimal
    IsOverdraft: bool
}

// Use discriminated unions to represent data of 1 or more forms
type WithdrawalResult =
    | Success of SuccessfulWithdrawal
    | InsufficientFunds of FailedWithdrawal
    | CardExpired of System.DateTime
    | UndisclosedFailure

F#registros y uniones discriminadas son distintos de null, inmutable y comparable de forma predeterminada, haciéndolos muy fácil de usar.F# records and discriminated unions are non-null, immutable, and comparable by default, making them very easy to use.

Corrección impuesto con funciones y coincidencia de patronesEnforced correctness with functions and pattern matching

F#las funciones son eficaces en la práctica y fácil declarar.F# functions are easy to declare and powerful in practice. Cuando se combina con coincidencia de patrones, le permiten definir comportamiento cuya corrección se aplica por el compilador.When combined with pattern matching, they allow you to define behavior whose correctness is enforced by the compiler.

// Returns a WithdrawalResult
let withdrawMoney amount = // Implementation elided

let handleWithdrawal amount =
    let w = withdrawMoney amount

    // The F# compiler enforces accounting for each case!
    match w with
    | Success s -> printfn "Successfully withdrew %f" s.Amount
    | InsufficientFunds f -> printfn "Failed: balance is %f" f.Balance
    | CardExpired d -> printfn "Failed: card expired on %O" d
    | UndisclosedFailure -> printfn "Failed: unknown :("

F#las funciones también son de primera clase, lo que significa que se pueden pasar como parámetros y devueltos por otras funciones.F# functions are also first-class, meaning they can be passed as parameters and returned from other functions.

Funciones para definir las operaciones en objetosFunctions to define operations on objects

F#es totalmente compatible con objetos, que son tipos de datos útiles cuando es necesario combinar datos y la funcionalidad.F# has full support for objects, which are useful data types when you need to blend data and functionality. F#las funciones se usan para manipular objetos.F# functions are used to manipulate objects.

type Set<[<EqualityConditionOn>] 'T when 'T: comparison>(elements: seq<'T>) =
    member s.IsEmpty = // Implementation elided
    member s.Contains (value) =// Implementation elided
    member s.Add (value) = // Implementation elided
    // ...
    // Further Implementation elided
    // ...
    interface IEnumerable<‘T>
    interface IReadOnlyCollection<‘T>

[<RequireQualifiedAccess>]
module Set =
    let isEmpty (set: Set<'T>) = set.IsEmpty

    let contains element (set: Set<'T>) = set.Contains(element)

    let add value (set: Set<'T>) = set.Add(value)

En lugar de escribir código que está orientada a objetos, en F#, a menudo escribirá código que se trata como otro tipo de datos para las funciones para manipular los objetos.Rather than writing code that is object-oriented, in F#, you will often write code that treats objects as another data type for functions to manipulate. Características como interfaces genéricas, expresiones de objetoy un uso razonable de miembros son comunes en mayor F# programas.Features such as generic interfaces, object expressions, and judicious use of members are common in larger F# programs.

Pasos siguientesNext steps

Para obtener más información sobre un conjunto mayor de F# características, consulte el F# paseo.To learn more about a larger set of F# features, check out the F# Tour.