Qortora · Search · Indexed page

fsharp.orgFetched 2026-08-14T02:51:30Z

fsharp.org

fsharp.org { if (this.theme === null) { if (e.matches) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } } }); } }" x-init="initDarkMode()" @click.away="mobileNavOpen = false"> fsharp.org Learn Learn F# Books Documenta…

Open original source · Full cached text

fsharp.org { if (this.theme === null) { if (e.matches) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } } }); } }" x-init="initDarkMode()" @click.away="mobileNavOpen = false"> fsharp.org Learn Learn F# Books Documentation Papers and Publications Videos (FSSF channel) Videos (Community) Use F# on Mac F# on Linux F# on Windows F# for Desktop Apps F# for Mobile Apps F# for Web Apps F# for Jupyter Notebooks F# in the browser Guides Cloud Data Access Data Science Enterprise Mobile Apps Web Testimonials Testimonials Submit Testimonial Community Contribute a Fix / Report an Issue F# Community Projects F# Code Snippets Amplifying F# Slack Discord Bluesky Reddit LinkedIn StackOverflow Foundation Code of Conduct F# Logo F# empowers everyone to write succinct, robust and performant code Use F# F# on Mac F# on Linux F# on Windows F# for Desktop Apps F# for Mobile Apps F# for Web Apps F# for Jupyter Notebooks F# in the browser F# gives you simplicity like Python with correctness, robustness and performance beyond C# or Java. F# is open source, cross-platform and free to use with professional tooling. F# is a JavaScript and .NET language for web, cloud, data-science, apps and more. HelloWorld.fs let hello name = printfn $"Hello, {name}!" let greets = [ "World" "Solar System" "Galaxy" "Universe" "Omniverse" ] greets |> List.iter hello Concise like Python F#’s elegant syntax and strong typing give you the tools to solve problems succinctly, robustly and happily. Concise like Python F#’s elegant syntax and strong typing give you the tools to solve problems succinctly, robustly and happily. Concise syntax defines reusable functions with minimal boilerplate Simple lists uses indentation-based syntax without requiring commas String interpolation provides readable string formatting with the $ prefix Pipeline operator creates a readable left-to-right flow of data In just a few lines of code, F# provides a clean, readable implementation that would require significantly more boilerplate in many other languages. This expressive style becomes even more valuable as your programs grow in complexity. OOP.fs // Interface definition type ICalculator = abstract Add: x: int -> y: int -> int abstract Multiply: x: int -> y: int -> int // Class implementation with interface type Calculator(precision: int) = // Interface implementation interface ICalculator with member _.Add x y = x + y member _.Multiply x y = x * y // Public methods member _.Subtract(x, y) = x - y // Method using property member _.RoundToPrecision(value: float) = System.Math.Round(value, precision) // Method with default parameter member _.Power(x: float, ?exponent: float) = let exp = defaultArg exponent 2.0 System.Math.Pow(x, exp) // Object expression (anonymous implementation) let quickCalc = { new ICalculator with member _.Add x y = x + y member _.Multiply x y = x * y } // Type extension - add method to existing type type System.Int32 with member x.IsEven = x % 2 = 0 Objects Made Simple F# is functional first and immutable by default, but it also provides pragmatic support for object programming. Objects Made Simple F# is functional first and immutable by default, but it also provides pragmatic support for object programming. Seamless .NET integration lets you work with existing .NET libraries and frameworks Rich interface system allows you to define clear contracts for your components Object expressions provide lightweight implementation of interfaces without defining full classes Concise member syntax keeps methods and properties clean and readable Automatic property generation reduces boilerplate code for data-carrying types Type extensions let you add methods to existing types without inheritance PaymentSystem.fs type CardInfo = { Number: string; Expiry: string; Cvv: string } type BankInfo = { AccountNumber: string; RoutingNumber: string } type PayPalInfo = { Email: string; Token: string } type PaymentMethod = | CreditCard of CardInfo | BankTransfer of BankInfo | PayPal of PayPalInfo type Payment = { Amount: decimal Method: PaymentMethod } let processPayment payment = match payment.Method with | CreditCard card -> printfn "Processing $%.2f via card %s" payment.Amount card.Number | BankTransfer bank -> printfn "Processing $%.2f via bank account %s" payment.Amount bank.AccountNumber | PayPal pp -> printfn "Processing $%.2f via PayPal account %s" payment.Amount pp.Email Domain Models made Simple and Safe Domain Models made Simple and Safe F# gives you superb capabilities to create precise domain models that prevent errors at compile time. Discriminated unions model each payment method with exactly the fields it needs No “impossible” states can exist - a credit card payment can’t have a routing number Exhaustive pattern matching ensures every payment type is handled properly Type safety catches errors at compile time that would be runtime bugs in other languages By modeling your domain using F#’s algebraic data types, you create self-documenting code where the type system itself enforces business rules. This powerful technique shifts many bugs from runtime to compile time, dramatically improving software reliability. WebApps.fs open Browser.Dom open Feliz // DOM manipulation let button = document.createElement("button") button.textContent <- "Click me!" button.addEventListener("click", fun _ -> window.alert("Hello from F#!") ) document.body.appendChild(button) |> ignore // React component (Feliz) let counter = React.functionComponent(fun () -> let (count, setCount) = React.useState(0) Html.div [ Html.button [ prop.text "-" prop.onClick (fun _ -> setCount(count - 1) ) ] Html.span [prop.text count] Html.button [ prop.text "+" prop.onClick (fun _ -> setCount(count + 1) ) ] ] ) F# for JavaScript and the Full Stack F# is for both client and server. With F# web technologies, you can target JavaScript environments directly. This means you can use F# to build web applications, mobile apps, and even serverless functions that run in the cloud. F# for JavaScript and the Full Stack F# is for both client and server. With F# web technologies, you can target JavaScript environments directly. This means you can use F# to build web applications, mobile apps, and even serverless functions that run in the cloud. Type-safe DOM manipulation catches errors at compile time, not runtime Seamless React integration with hooks and modern patterns Full npm ecosystem access with clean TypeScript-like interop Simplified async programming with F#’s computation expressions for promises F# brings its powerful type system and immutability to frontend development, eliminating common JavaScript bugs while maintaining full access to the JavaScript ecosystem. TypeProviders.fs open FSharp.Data type PeopleDB = CsvProvider<"people.csv"> let printPeople () = let people = PeopleDB.Load("people.csv") for person in people.Rows do // Access the CSV fields with intellisense and type safety! printfn $"Name: %s{person.Name}, Id: %i{person.Id}" Type-Safe, Integrated Data F# Type Providers create a seamless bridge between your code and data sources. Type-Safe, Integrated Data F# Type Providers create a seamless bridge between your code and data sources. Zero-friction data access connects to CSV, JSON, XML, SQL, and more without manual mapping Static typing at compile time prevents runtime errors when accessing external data Automatic schema discovery creates F# types directly from sample data or schemas Full IDE integration provides intellisense for external data sources Design-time capabilities validate your code against live data sources before execution SequenceExpressions.fs let rec fizzBuzzSeq n = seq { match n with | x when x % 15 = 0 -> "fizzbuzz" | x when x % 3 = 0 -> "fizz" | x when x % 5 = 0 -> "buzz" | _ -> n.ToString() // Tail recursion makes this as efficient as a "while" loop yield! fizzBuzzSeq (n + 1) } // Process the sequence using a pipeline fizzBuzzSeq 1 |> Seq.take 100 |> Seq.iter (printfn "%s") Data Pipelines with Sequence Expressions F# sequence expressions provide compositional, functional stream processing capabilities that integrate seamlessly with every part of the language. Data Pipelines with Sequence Expressions F# sequence expressions provide compositional, functional stream processing capabilities that integrate seamlessly with every part of the language. Simplified data generation through sequence expressions Compositional data processing through library routines On-demand evaluation of data streams Fluent, maintainable code that is easy to read and understand AsyncExpressions.fs // An async function let fetchDataAsync url = async { printfn "Fetching data from %s..." url do! Async.Sleep 1000 // Simulate network delay return sprintf "Data from %s" url } // Using pattern matching in async code let processPersonAsync person = async { let result = validatePerson person.Age person.Name match result with | Ok validated -> return! fetchDataAsync $"profile/{validated.Name}" | Error msg -> return $"Validation error: {msg}" } processPersonAsync { Name = "Snowdrop"; Age = 13} |> Async.RunSynchronously Async Programming made Easy F# async expressions provide a powerful way to handle asynchronous programming, making it more readable and maintainable. They allow you to write non-blocking code that looks like synchronous code, which is particularly useful for I/O-bound operations. Async Programming made Easy F# async expressions provide a powerful way to handle asynchronous programming, making it more readable and maintainable. They allow you to write non-blocking code that looks like synchronous code, which is particularly useful for I/O-bound operations. Async expressions provide a clean syntax for defining asynchronous workflows Integration with existing libraries makes it easy to use async expressions with other F# features Error handling is simplified with the use of discriminated unions and pattern matching Seamless integration with F#’s type system ensures type safety and reduces runtime errors Support for cancellation and timeouts allows you to manage long-running operations effectively ComputationExpressions.fs // Define a custom computation expression for validation type ValidationBuilder() = member _.Bind(x, f) = // Defines "let!" match x with | Ok value -> f value | Error e -> Error e member _.Return(x) = Ok x // Defines "return" member _.ReturnFrom(x) = x // Defines "return!" let validate = ValidationBuilder() type Person = { Name: string; Age: int } // Use the custom computation expression let validatePerson age name = validate { let! validAge = if age >= 0 && age < 150 then Ok age else Error "Age must be between 0 and 150" let! nonEmptyName = if String.length name > 0 then Ok name else Error "Name cannot be empty" if String.length name > 100 then return! Error "Name is too long!" else return { Name = nonEmptyName; Age = validAge } } Clean Code with Computation Expressions F# computation expressions give you an elegant syntax for compositional control flows with a clean, readable notation that some say is F#’s superpower. Clean Code with Computation Expressions F# computation expressions give you an elegant syntax for compositional control flows with a clean, readable notation that some say is F#’s superpower. Computation expressions factor out how code is composed together Custom control flow abstractions create domain-specific mini-languages Seamless error handling with railway-oriented programming patterns Elegant data transformations by hiding boilerplate and focusing on business logic Composable workflows that can be combined and nested for complex operations UnitsOfMeasure.fs open FSharp.Data.UnitSystems.SI // Acceleration due to gravity let g = 9.81<m/s^2> // The return type is inferred as float<m> let distance ( t: float<s> ) = 0.5 * g * t * t let fallDuration = 2.0<s> let fallDistance = distance fallDuration printfn $"Distance fallen in {fallDuration}s is {fallDista…