F#是一种函数式编程语言,可以轻松编写正确且可维护的代码。
F#编程主要涉及定义类型推断和自动泛化的类型和函数。 这使您可以将焦点保留在问题域上并操纵其数据,而不是编程的细节。
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 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#有许多功能,包括:
// 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#记录和区分联合在默认情况下是非null,不可变和可比较的,使它们非常容易使用。
// 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 :("
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> 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)
原创版权所有,禁止未经授权的复制转载。喜欢就关注。
给作者留言