### Basic F#Plus Setup and Namespace Declaration Source: https://fsprojects.github.io/FSharpPlus/type-first This example demonstrates the fundamental steps to get started with F#Plus, including referencing the NuGet package in an F# interactive session or script, opening the main FSharpPlus namespace to access its functionalities, and declaring a namespace for organizing your F# code. ```F# #r @"nuget: FSharpPlus" ``` ```F# open FSharpPlus ``` ```F# namespace FSharpPlus ``` -------------------------------- ### F# FSharpPlus Library Setup and Namespace Declaration Source: https://fsprojects.github.io/FSharpPlus/type-choicet This snippet demonstrates the essential steps to prepare an F# project for using the FSharpPlus library. It includes referencing the necessary DLL, opening the main FSharpPlus namespace, and declaring a namespace for the F# code. ```F# #r @"../../src/FSharpPlus/bin/Release/netstandard2.0/FSharpPlus.dll" open FSharpPlus namespace FSharpPlus ``` -------------------------------- ### FSharpPlus Basic Setup and Namespace Usage Source: https://fsprojects.github.io/FSharpPlus/type-coproduct This snippet demonstrates the fundamental steps to integrate and begin using the FSharpPlus library in an F# project or interactive session. It covers referencing the NuGet package, opening the main namespace, and declaring a namespace for project organization. ```F# #r @"nuget: FSharpPlus" ``` ```F# open FSharpPlus ``` ```F# namespace FSharpPlus ``` -------------------------------- ### Install FSharpPlus and Use String Extension Source: https://fsprojects.github.io/FSharpPlus/index This example demonstrates how to install the FSharpPlus NuGet package using an F# interactive directive and then utilize an extension function, `String.replace`, provided by the library to modify a string. ```F# #r @"nuget: FSharpPlus" ``` ```F# open FSharpPlus let x = String.replace "old" "new" "Good old days" // val x : string = "Good new days" ``` -------------------------------- ### F# Free Monad Command-Line Wizard Example Source: https://fsprojects.github.io/FSharpPlus/type-free This comprehensive F# code snippet illustrates the implementation of a Free Monad pattern to create a pure command-line wizard. It defines a `CommandLineInstruction` type, lifts basic I/O operations into the Free Monad, and provides an `interpretCommandLine` function to execute these instructions. The example includes functions for reading various user inputs (quantity, date, name, email) and combines them to create a `Reservation` object, showcasing how to separate program description from its interpretation. ```F# open System open FSharpPlus open FSharpPlus.Data type CommandLineInstruction<'t> = | ReadLine of (string -> 't) | WriteLine of string * 't with static member Map (x, f) = match x with | ReadLine g -> ReadLine (f << g) | WriteLine (s, g) -> WriteLine (s, f g) let readLine = Free.liftF (ReadLine id) let writeLine s = Free.liftF (WriteLine (s, ())) let rec interpretCommandLine = Free.run >> function | Pure x -> x | Roll (ReadLine next) -> Console.ReadLine () |> next |> interpretCommandLine | Roll (WriteLine (s, next)) -> Console.WriteLine s next |> interpretCommandLine let rec readQuantity = monad { do! writeLine "Please enter number of diners:" let! l = readLine match tryParse l with | Some dinerCount -> return dinerCount | None -> do! writeLine "Not an integer." return! readQuantity } let rec readDate = monad { do! writeLine "Please enter your desired date:" let! l = readLine match DateTimeOffset.TryParse l with | true, dt -> return dt | _ -> do! writeLine "Not a date." return! readDate } let readName = monad { do! writeLine "Please enter your name:" return! readLine } let readEmail = monad { do! writeLine "Please enter your email address:" return! readLine } type Reservation = { Date : DateTimeOffset Name : string Email : string Quantity : int } with static member Create (Quantity, Date, Name, Email) = { Date = Date; Name = Name; Email = Email; Quantity = Quantity } let readReservationRequest = curryN Reservation.Create readQuantity <*> readDate <*> readName <*> readEmail let mainFunc () = readReservationRequest >>= (writeLine << (sprintf "%A")) |> interpretCommandLine 0 ``` -------------------------------- ### F# List.apply Function API and Example Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-list Detailed API documentation for the `List.apply` function in FSharpPlus, including its signature, parameters, return type, and a usage example demonstrating how to apply a list of functions to a list of values. ```APIDOC List.apply f x Parameters: f : ('T -> 'U) list - The list of functions. x : 'T list - The list of values. Returns: 'U list - A concatenated list of the result lists of applying each function to each value ``` ```F# > List.apply [double; triple] [1; 2; 3];; val it : int list = [2; 4; 6; 3; 6; 9] ``` -------------------------------- ### Reference FSharpPlus Assembly and Open Namespace Source: https://fsprojects.github.io/FSharpPlus/type-statet This F# code snippet illustrates how to reference the FSharpPlus assembly and open its namespace. This is a common first step in an F# script or project to make the library's functions and types accessible for use. ```F# #r @"../../src/FSharpPlus/bin/Release/netstandard2.0/FSharpPlus.dll" open FSharpPlus ``` -------------------------------- ### API Documentation and Examples for List.take Function Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-list Documents the `List.take` function, which returns the first N elements of a list. It includes details on parameters, return types, potential exceptions (`ArgumentException`, `InvalidOperationException`), and notes its deprecation in FSharpPlus due to its inclusion in FSharp.Core. Examples demonstrate its usage and behavior with different inputs. ```APIDOC List.take count list Parameters: count: int - The number of items to take. list: 'T list - The input list. Returns: 'T list - The result list. Description: Returns the first N elements of the list. Exceptions: ArgumentException: Thrown when the input list is empty. InvalidOperationException: Thrown when count exceeds the number of elements in the list. Note: This function has since been added to FSharp.Core. It will be removed in next major release of FSharpPlus. Module/Type Info: module List from Microsoft.FSharp.Collections type List<'T> = | op_Nil | op_ColonColon of Head: 'T * Tail: 'T list interface IReadOnlyList<'T> interface IReadOnlyCollection<'T> interface IEnumerable interface IEnumerable<'T> member GetReverseIndex: rank: int * offset: int -> int member GetSlice: startIndex: int option * endIndex: int option -> 'T list static member Cons: head: 'T * tail: 'T list -> 'T list member Head: 'T member IsEmpty: bool member Item: index: int -> 'T with get val take: count: int -> list: 'T list -> 'T list ``` ```F# let inputs = ["a"; "b"; "c"; "d"] inputs |> List.take 2 ``` ```F# let inputs = ["a"; "b"; "c"; "d"] inputs |> List.take 6 ``` ```F# let inputs = ["a"; "b"; "c"; "d"] inputs |> List.take 0 ``` -------------------------------- ### F# State Monad Game Example Source: https://fsprojects.github.io/FSharpPlus/type-state An example demonstrating the use of the F# State monad to simulate a simple game where state (on/off, score) is managed functionally. It shows how to use `State.get`, `State.put`, `State.eval`, and `State.run`. ```F# let rec playGame = function | []-> monad { let! (_, score) = State.get return score } | x::xs-> monad { let! (on, score) = State.get match x with | 'a' when on -> do! State.put (on, score + 1) | 'b' when on -> do! State.put (on, score - 1) | 'c' -> do! State.put (not on, score) | _ -> do! State.put (on, score) return! playGame xs } let startState = (false, 0) let moves = toList "abcaaacbbcabbab" State.eval (playGame moves) startState let (score, finalState) = State.run (playGame moves) startState ``` -------------------------------- ### Implement a Basic Web Crawler with F#+ SeqT Source: https://fsprojects.github.io/FSharpPlus/type-seqt This F# example illustrates building a simple web crawler using FSharpPlus's SeqT and HtmlAgilityPack. It includes helper functions for asynchronous document download, link extraction from HTML, and title retrieval. The core randomCrawl function recursively traverses links, yielding visited URLs and their titles, demonstrating advanced asynchronous sequence processing. ```F# // A simple webcrawler #r "nuget: FSharpPlus,1.3.0-CI02744" #r "nuget: HtmlAgilityPack" open System open System.Net open System.Text.RegularExpressions open HtmlAgilityPack open FSharp.Control open FSharpPlus open FSharpPlus.Data // ---------------------------------------------------------------------------- // Helper functions for downloading documents, extracting links etc. /// Asynchronously download the document and parse the HTML let downloadDocument url = async { try let wc = new WebClient () let! html = wc.AsyncDownloadString (Uri url) let doc = new HtmlDocument () doc.LoadHtml html return Some doc with _ -> return None } /// Extract all links from the document that start with "http://" let extractLinks (doc:HtmlDocument) = try [ for a in doc.DocumentNode.SelectNodes ("//a") do if a.Attributes.Contains "href" then let href = a.Attributes.["href"].Value if href.StartsWith "https://" then let endl = href.IndexOf '?' yield if endl > 0 then href.Substring(0, endl) else href ] with _ -> [] /// Extract the of the web page let getTitle (doc: HtmlDocument) = let title = doc.DocumentNode.SelectSingleNode "//title" if title <> null then title.InnerText.Trim () else "Untitled" // ---------------------------------------------------------------------------- // Basic crawling - crawl web pages and follow just one link from every page /// Crawl the internet starting from the specified page /// From each page follow the first not-yet-visited page let rec randomCrawl url = let visited = new System.Collections.Generic.HashSet<_> () // Visits page and then recursively visits all referenced pages let rec loop url = monad.plus { if visited.Add(url) then let! doc = downloadDocument url |> SeqT.lift match doc with | Some doc -> // Yield url and title as the next element yield url, getTitle doc // For every link, yield all referenced pages too for link in extractLinks doc do yield! loop link | _ -> () } loop url // Use SeqT combinators to print the titles of the first 10 // web sites that are from other domains than en.wikipedia.org randomCrawl "https://en.wikipedia.org/wiki/Main_Page" |> SeqT.filter (fun (url, title) -> url.Contains "en.wikipedia.org" |> not) |> SeqT.map snd |> SeqT.take 10 |> SeqT.iter (printfn "%s") |> Async.Start ``` -------------------------------- ### Install FSharpPlus NuGet Package Source: https://fsprojects.github.io/FSharpPlus/type-all This snippet shows how to reference the FSharpPlus NuGet package in an F# interactive environment or script, making its functionalities available for use. ```F# #r @"nuget: FSharpPlus" ``` -------------------------------- ### Demonstrating Exception Protection with FSharpPlus Source: https://fsprojects.github.io/FSharpPlus/extensions This example illustrates how `Result.protect` and `Option.protect` can be used to handle exceptions gracefully, converting them into `Result.Error` or `None` respectively, instead of throwing. ```F# // throws "ArgumentException: The input sequence was empty." let expectedSingleItem1 : int = List.exactlyOne [] // returns a Result.Error holding the exception as its value: let expectedSingleItem2 : Result<int,exn> = Result.protect List.exactlyOne [] // ...or like typical try prefixed functions, treat exception as None let expectedSingleItem3 : Option<int> = Option.protect List.exactlyOne [] // which might look like this: let inline tryExactlyOne xs = Option.protect List.exactlyOne xs ``` -------------------------------- ### FSharpPlus Core Type and Value Definitions API Source: https://fsprojects.github.io/FSharpPlus/type-compose API documentation for fundamental type aliases and specific value definitions found in the FSharpPlus context. This includes the `int` and `string` type aliases, and pre-defined `Async<Result>` values (`one`, `two`) used in examples, along with the `async` computation expression builder. ```APIDOC val one: Async<Result<int,string>> type Async<'T> val int: value: 'T -> int (requires member op_Explicit) type int = int32 type int<'Measure> = int val string: value: 'T -> string type string = System.String val async: AsyncBuilder val two: Async<Result<int,string>> ``` -------------------------------- ### FSharpPlus Core Functionality Examples in F# Source: https://fsprojects.github.io/FSharpPlus/abstraction-misc Demonstrates various FSharpPlus features including Indexable operations (mapi, iteri, foldi, traversei), Collection manipulations (skip, chunkBy), Reducibles (nelist, reduce, choice), and Invariant Functor usage (StringConverter, invmap) with concrete F# code. ```F# #r @"../../src/FSharpPlus/bin/Release/netstandard2.0/FSharpPlus.dll" open System open FSharpPlus open FSharpPlus.Data // Indexable let namesWithNdx = mapi (fun k v -> "(" + string k + ")" + v ) (Map.ofSeq ['f',"Fred";'p',"Paul"]) let namesAction = iteri (printfn "(%A)%s") (Map.ofSeq ['f',"Fred";'p',"Paul"]) let res119 = foldi (fun s i t -> t * s - i) 10 [3;4] let res113 = foldi (fun s i t -> t * s - i) 2 [|3;4;5|] let resSomeId20 = traversei (fun k t -> Some (10 + t)) (Tuple 10) // Collection let a = skip 3 [1..10] let b = chunkBy fst [1, "a"; 1, "b"; 2, "c"; 1, "d"] // Reducibles let c = nelist {1; 2; 3} let d = reduce (+) c let resultList = nelist {Error "1"; Error "2"; Ok 3; Ok 4; Error "5"} let firstOk = choice resultList // Invariant Functor type StringConverter<'t> = StringConverter of (string -> 't) * ('t -> string) with static member Invmap (StringConverter (f, g), f',g') = StringConverter (f' << f, g << g') let ofString (StringConverter (f, _)) = f let toString (StringConverter (_, f)) = f let floatConv = StringConverter (float<string>, string<float>) let floatParsed = ofString floatConv "1.8" let floatEncoded = toString floatConv 1.5 let intConv = invmap int<float> float<int> floatConv let oneParsed = ofString intConv "1" let tenEncoded = toString intConv 10 ``` -------------------------------- ### System.Collections.Generic.HashSet Class Constructors Source: https://fsprojects.github.io/FSharpPlus/type-seqt Documents the various constructor overloads available for the `System.Collections.Generic.HashSet` class in .NET, allowing instantiation with different initial collections, comparers, or capacities. ```APIDOC Collections.Generic.HashSet() : Collections.Generic.HashSet<'T> Collections.Generic.HashSet(collection: Collections.Generic.IEnumerable<'T>) : Collections.Generic.HashSet<'T> Collections.Generic.HashSet(comparer: Collections.Generic.IEqualityComparer<'T>) : Collections.Generic.HashSet<'T> Collections.Generic.HashSet(capacity: int) : Collections.Generic.HashSet<'T> Collections.Generic.HashSet(collection: Collections.Generic.IEnumerable<'T>, comparer: Collections.Generic.IEqualityComparer<'T>) : Collections.Generic.HashSet<'T> Collections.Generic.HashSet(capacity: int, comparer: Collections.Generic.IEqualityComparer<'T>) : Collections.Generic.HashSet<'T> ``` -------------------------------- ### F# Async Applicative Functor Interactive Input Example Source: https://fsprojects.github.io/FSharpPlus/applicative-functors This F# example demonstrates the practical use of the 'Async' applicative functor by creating an asynchronous computation that reads multiple lines of input from the console. It showcases how 'pure'' and '<*>' can be used to combine interactive I/O operations in an asynchronous, applicative manner. ```F# let getLine = async { let x = System.Console.ReadLine() return System.Int32.Parse x } let r24 = pure' (+) <*> getLine <*> getLine ``` -------------------------------- ### Install FSharpPlus NuGet Package Source: https://fsprojects.github.io/FSharpPlus/type-nonempty This snippet shows how to reference the FSharpPlus NuGet package in an F# interactive environment or script. ```F# #r @"nuget: FSharpPlus" ``` -------------------------------- ### Convert Bytes to Guid (BitConverter.ToGuid) Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-internals-bitconverter Converts a specified range of bytes from a byte array into a Guid structure. This method takes the byte array, a starting index, and an indicator for endianness. ```APIDOC BitConverter.ToGuid(value: byte[], startIndex: int, isLittleEndian: bool) value: byte[] startIndex: int isLittleEndian: bool Returns: Guid ``` -------------------------------- ### Basic FSharpPlus Setup and Map/Applicative Usage Source: https://fsprojects.github.io/FSharpPlus/abstraction-applicative Demonstrates fundamental FSharpPlus operations including referencing the NuGet package, opening necessary modules, applying functions to lists and arrays using 'map', and basic applicative application with '<*>' and '<!>' operators for optional values. ```F# #r @"nuget: FSharpPlus" open FSharpPlus open FSharpPlus.Data // Apply +4 to a list let lst5n6 = map ((+) 4) [ 1; 2 ] // Apply +4 to an array let arr5n6 = map ((+) 4) [|1; 2|] // I could have written this let arr5n6' = (+) <!> [|4|] <*> [|1; 2|] // Add two options let opt120 = (+) <!> Some 20 <*> tryParse "100" ``` -------------------------------- ### List.GetSlice Method (F#) Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-extensions Defines a method for getting a slice from an `List` collection in FSharpPlus. This allows extracting a sub-list based on optional start and end indices. ```APIDOC this.GetSlice: Full Usage: this.GetSlice Parameters: (): unit Returns: int option * int option -> List<'T> Extended Type: List ``` -------------------------------- ### System.Tuple Types API Documentation Source: https://fsprojects.github.io/FSharpPlus/abstraction-misc API documentation for the `System.Tuple` types, including static methods for creating tuples and definitions for 1-tuple (`Tuple<'T1>`) and n-tuple (`Tuple<'T1,...,'TRest>`) with their interfaces and members. ```APIDOC Multiple items type Tuple = static member Create<'T1> : item1: 'T1 -> Tuple<'T1> + 7 overloads *<summary>Provides static methods for creating tuple objects.</summary>* -------------------- type Tuple<'T1> = interface IStructuralComparable interface IStructuralEquatable interface IComparable interface ITuple new: item1: 'T1 -> unit member Equals: obj: obj -> bool member GetHashCode: unit -> int member ToString: unit -> string member Item1: 'T1 *<summary>Represents a 1-tuple, or singleton.</summary> <typeparam name="T1">The type of the tuple's only component.</typeparam>* -------------------- -------------------- -------------------- -------------------- -------------------- -------------------- type Tuple<'T1,'T2,'T3,'T4,'T5,'T6,'T7,'TRest> = interface IStructuralComparable interface IStructuralEquatable interface IComparable interface ITuple new: item1: 'T1 \* item2: 'T2 \* item3: 'T3 \* item4: 'T4 \* item5: 'T5 \* item6: 'T6 \* item7: 'T7 \* rest: 'TRest -> unit member Equals: obj: obj -> bool member GetHashCode: unit -> int member ToString: unit -> string member Item1: 'T1 member Item2: 'T2 ... *<summary>Represents an n-tuple, where n is 8 or greater.</summary>* ``` -------------------------------- ### IEnumerable.GetSlice Method Overloads (F#) Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-extensions Defines methods for getting a slice from an `IEnumerable` collection in FSharpPlus. This allows extracting a sub-sequence based on optional start and end indices. ```APIDOC this.GetSlice: Full Usage: this.GetSlice Parameters: (): unit Returns: int option * int option -> IEnumerable<'T> Extended Type: IEnumerable ``` ```APIDOC this.GetSlice: Full Usage: this.GetSlice Returns: int option * int option -> IEnumerable<'T> Modifiers: abstract Extended Type: IEnumerable ``` -------------------------------- ### FSharpPlus Random Web Crawl Utility Source: https://fsprojects.github.io/FSharpPlus/type-seqt A utility function for performing a simple web crawl, starting from a specified URL. From each visited page, it attempts to follow the first not-yet-visited link. ```APIDOC val randomCrawl: url: string -> SeqT<Async<bool>,(string * string)> ``` -------------------------------- ### Create Guid byte conversion function Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-control-ofbytes Creates a function that converts a byte array to a `System.Guid`, given an `OfBytes` context. The returned function takes a byte array, start index, and endianness. ```APIDOC OfBytes.OfBytes(targetType: Guid, context: OfBytes) -> (byte[] * int * bool -> Guid) targetType: Guid - The target type for the conversion. context: OfBytes - The OfBytes context. Returns: (byte[] * int * bool -> Guid) - A function that takes a byte array, start index, and endianness, and returns a Guid. ``` -------------------------------- ### FSharpPlus Matrix and Related API Reference Source: https://fsprojects.github.io/FSharpPlus/type-matrix This section provides API documentation for key types and functions related to the 'Matrix' type in FSharpPlus, including type signatures for matrix instances, the 'matrix' constructor function, and the 'result' function for lifting values into a Functor. It also includes details for the 'Generic' module in 'FSharpPlus.Math'. ```APIDOC namespace FSharpPlus namespace FSharpPlus.Data val matrix3x4_1: Matrix<int,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>>> val matrix: definition: '('a * .. * 'a) * .. * ('a * .. * 'a) -> Matrix<'a0,'m,'n> (requires member CountTuple and member TupleToList and member RuntimeValue and member CountTuple and member TupleToList and member RuntimeValue) val matrix3x4_2: Matrix<int,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>>> val matrix3x4_sum: Matrix<int,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>>> val matrix3x4_3: Matrix<int,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>>> val result: x: 'T -> 'Functor<'T> (requires member Return) Summary: Lifts a value into a Functor. Same as return in Computation Expressions. Category: Applicative namespace FSharpPlus.Math module Generic from FSharpPlus.Math Summary: Generic numbers, functions and operators. By opening this module some common operators become restricted, like (+) to 'T->'T->'T val vector3d_4: Matrix<int,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>,TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.S<TypeLevel.Z>>>>> ``` -------------------------------- ### FSharpPlus HTML Document Utility Functions Source: https://fsprojects.github.io/FSharpPlus/type-seqt Utility functions for extracting specific data from an HtmlDocument. This includes extracting all links starting with 'http://' and extracting the text content of the '<title>' tag. ```APIDOC val extractLinks: doc: HtmlDocument -> string list val getTitle: doc: HtmlDocument -> string ``` -------------------------------- ### FSharpPlus Map Module and Type API Reference Source: https://fsprojects.github.io/FSharpPlus/tutorial API documentation for the `Map` module from `FSharpPlus` and `Microsoft.FSharp.Collections`, detailing its interfaces, constructors (including one from a sequence of key-value pairs), and members like `Add`. ```APIDOC module Map from FSharpPlus *<summary> Additional operations on Map<'Key, 'Value> </summary>* -------------------- module Map from Microsoft.FSharp.Collections -------------------- type Map<'Key,'Value (requires comparison)> = interface IReadOnlyDictionary<'Key,'Value> interface IReadOnlyCollection<KeyValuePair<'Key,'Value>> interface IEnumerable interface IStructuralEquatable interface IComparable interface IEnumerable<KeyValuePair<'Key,'Value>> interface ICollection<KeyValuePair<'Key,'Value>> interface IDictionary<'Key,'Value> new: elements: ('Key \* 'Value) seq -> Map<'Key,'Value> member Add: key: 'Key \* value: 'Value -> Map<'Key,'Value> ... -------------------- new: elements: ('Key \* 'Value) seq -> Map<'Key,'Value> ``` -------------------------------- ### FSharpPlus Initial Setup and Assertions Source: https://fsprojects.github.io/FSharpPlus/type-cont This snippet demonstrates how to reference the FSharpPlus NuGet package and define a helper function `assertEqual` for testing purposes, used throughout the examples to verify computation results. ```F# #r @"nuget: FSharpPlus" open FSharpPlus open FSharpPlus.Data let assertEqual expected actual = if expected <> actual then failwithf "%A != %A" expected actual ``` -------------------------------- ### FSharpPlus TryFinally.TryFinally Function Overloads Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-control-tryfinally Comprehensive API documentation for the `TryFinally.TryFinally` function, detailing its multiple signatures, parameters, and return types for different monadic contexts and control flow scenarios within the FSharpPlus library. ```APIDOC TryFinally.TryFinally(arg1, arg2, arg3, _defaults) Parameters: arg0: (unit -> 'Monad<'T>) * (unit -> unit) arg1: Default3 arg2: Default2 _defaults: False Returns: 'a TryFinally.TryFinally(arg1, arg2, arg3, arg4) Parameters: arg0: (unit -> Lazy<'a>) * (unit -> unit) arg1: TryFinally arg2: 'b arg3: 'c Returns: Lazy<'a> TryFinally.TryFinally(arg1, arg2, arg3, True) Parameters: arg0: (unit -> Task<'a>) * (unit -> unit) arg1: TryFinally arg2: 'b True: True Returns: Task<'a> TryFinally.TryFinally(arg1, arg2, arg3, arg4) Parameters: arg0: (unit -> Async<'a>) * (unit -> unit) arg1: TryFinally arg2: 'b arg3: 'c Returns: Async<'a> TryFinally.TryFinally(arg1, arg2, arg3, arg4) Parameters: arg0: (unit -> Id<'a>) * (unit -> unit) arg1: TryFinally arg2: 'b arg3: 'c Returns: Id<'a> TryFinally.TryFinally(arg1, arg2, arg3, _defaults) Parameters: arg0: (unit -> 'R -> 'a) * (unit -> unit) arg1: Default2 arg2: 'b _defaults: True Returns: 'R -> 'a ``` -------------------------------- ### API Documentation for FSharpPlus.Data.Dual Module Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-data-dual Provides API details for the Dual module, which contains basic operations. It is part of the FSharpPlus.Data namespace and is found in the FSharpPlus.dll assembly. This section specifically documents the `Dual.run` function. ```APIDOC Module: Dual Namespace: FSharpPlus.Data Assembly: FSharpPlus.dll Description: Basic operations on Dual Function: Dual.run Full Usage: Dual.run arg1 Parameters: arg0: Dual<'T> Returns: 'T ``` -------------------------------- ### .NET String Manipulation Methods Source: https://fsprojects.github.io/FSharpPlus/type-seqt Common .NET methods for string operations, including checking if a string starts with a specified value, finding the index of a substring or character, extracting substrings, and trimming whitespace or specified characters. ```APIDOC String.StartsWith(value: string) : bool String.StartsWith(value: char) : bool String.StartsWith(value: string, comparisonType: StringComparison) : bool String.StartsWith(value: string, ignoreCase: bool, culture: Globalization.CultureInfo) : bool String.IndexOf(value: string) : int String.IndexOf(value: char) : int String.IndexOf(value: string, comparisonType: StringComparison) : int String.IndexOf(value: string, startIndex: int) : int String.IndexOf(value: char, comparisonType: StringComparison) : int String.IndexOf(value: char, startIndex: int) : int String.IndexOf(value: string, startIndex: int, comparisonType: StringComparison) : int String.IndexOf(value: string, startIndex: int, count: int) : int String.IndexOf(value: char, startIndex: int, count: int) : int String.IndexOf(value: string, startIndex: int, count: int, comparisonType: StringComparison) : int String.Substring(startIndex: int) : string String.Substring(startIndex: int, length: int) : string String.Trim() : string String.Trim([<ParamArray>] trimChars: char array) : string String.Trim(trimChar: char) : string ``` -------------------------------- ### Standard F# Library Functions API Documentation Source: https://fsprojects.github.io/FSharpPlus/abstraction-misc API documentation for common F# library functions such as `string` conversion, `printfn` for formatted printing, and the `Option.Some` union case. ```APIDOC Multiple items val string: value: 'T -> string Multiple items val printfn: format: Printf.TextWriterFormat<'T> -> 'T union case Option.Some: Value: 'T -> Option<'T> ``` -------------------------------- ### System.Uri API Reference Source: https://fsprojects.github.io/FSharpPlus/type-seqt Detailed API documentation for the System.Uri type, including its various constructors for creating URI instances, and members for manipulating and querying URI components. This section also covers methods for relative URI operations and serialization. ```APIDOC type Uri = interface ISerializable new: uriString: string -> unit + 6 overloads member Equals: comparand: obj -> bool member GetComponents: components: UriComponents * format: UriFormat -> string member GetHashCode: unit -> int member GetLeftPart: part: UriPartial -> string member IsBaseOf: uri: Uri -> bool member IsWellFormedOriginalString: unit -> bool member MakeRelative: toUri: Uri -> string member MakeRelativeUri: uri: Uri -> Uri Constructors: Uri(uriString: string) : Uri Uri(uriString: string, creationOptions: inref<UriCreationOptions>) : Uri Uri(uriString: string, uriKind: UriKind) : Uri Uri(baseUri: Uri, relativeUri: string) : Uri Uri(baseUri: Uri, relativeUri: Uri) : Uri ``` -------------------------------- ### F# Option Applicative Functor Step-by-Step Implementation Source: https://fsprojects.github.io/FSharpPlus/applicative-functors This F# example demonstrates the manual implementation of 'step1' and 'step2' for the 'Option' type. 'step1' lifts a function into an 'Option' context, while 'step2' applies a function wrapped in an 'Option' to a value wrapped in an 'Option', returning an 'Option' result. It shows how these steps can be chained to process optional values. ```F# let step1 f = Some f let step2 a b = match a, b with | Some f, Some x -> Some (f x) | _ -> None let r16 = step1 (fun x -> string (x + 10)) let r17 = step2 r16 (Some 5) ``` -------------------------------- ### F#Plus Tuple Constructors API Source: https://fsprojects.github.io/FSharpPlus/abstraction-misc Documents the various constructors available in F#Plus for creating tuples with a flexible number of components. These constructors simplify the creation of tuples up to seven elements, with an additional generic component for larger structures. ```APIDOC Tuple Constructors: type_parameters: T1: The type of the tuple's first component. T2: The type of the tuple's second component. T3: The type of the tuple's third component. T4: The type of the tuple's fourth component. T5: The type of the tuple's fifth component. T6: The type of the tuple's sixth component. T7: The type of the tuple's seventh component. TRest: Any generic ``` -------------------------------- ### F# Traversal for Collection Manipulation Source: https://fsprojects.github.io/FSharpPlus/lens Illustrates the use of Traversal in F# for operating on multiple elements within a collection. Examples include using `setl` to modify all matching elements, `preview` to get the first matching element, `toListOf` to extract all matching elements into a list, and `view` for monoidal aggregation. ```F# let t1 = [|"Something"; ""; "Something Else"; ""|] |> setl (_all "") ("Nothing") // val t1 : string [] = [|"Something"; "Nothing"; "Something Else"; "Nothing"| // we can preview it let t2 = [|"Something"; "Nothing"; "Something Else"; "Nothing"|] |> preview (_all "Something") // val t2 : string option = Some "Something" // view all elements in a list let t3 = [|"Something"; "Nothing"; "Something Else"; "Nothing"|] |> toListOf (_all "Something") // val t3 : string list = ["Something"] // also view it, since string is a monoid let t4 = [|"Something"; "Nothing"; "Something Else"; "Nothing"|] |> view (_all "Something") // val t4 : string = "Something" // Lens composed with a Traversal -> Traversal let t5 = [((), "Something"); ((),""); ((), "Something Else"); ((),"")] |> preview (_all ((),"Something") << _2) // val t5 : Option<string> = Some "Something" ``` -------------------------------- ### F# Validation Result Examples Source: https://fsprojects.github.io/FSharpPlus/type-validation Illustrates various outcomes of validation operations for a `Person` object, showing examples of successful and failed validations to demonstrate different error scenarios and the `Validation` type's behavior. ```F# val validPerson: Validation<Error list,Person> ``` ```F# val badName: Validation<Error list,Person> ``` ```F# val badEmail: Validation<Error list,Person> ``` ```F# val badAge: Validation<Error list,Person> ``` ```F# val badEverything: Validation<Error list,Person> ``` -------------------------------- ### System.Net.WebClient Class API Reference Source: https://fsprojects.github.io/FSharpPlus/type-seqt This section provides API documentation for the System.Net.WebClient class, detailing its constructor, inherited members, and various methods for downloading data and files. It covers both synchronous and asynchronous operations, including methods for downloading strings, byte arrays, and files, along with their overloads. ```APIDOC namespace System namespace System.Net type WebClient = inherit Component new: unit -> unit member CancelAsync: unit -> unit member DownloadData: address: string -> byte array + 1 overload member DownloadDataAsync: address: Uri -> unit + 1 overload member DownloadDataTaskAsync: address: string -> Task<byte array> + 1 overload member DownloadFile: address: string * fileName: string -> unit + 1 overload member DownloadFileAsync: address: Uri * fileName: string -> unit + 1 overload member DownloadFileTaskAsync: address: string * fileName: string -> Task + 1 overload member DownloadString: address: string -> string + 1 overload ... <summary>Provides common methods for sending data to and receiving data from a resource identified by a URI.</summary> val wc: System.Net.WebClient ``` -------------------------------- ### F# Example Usage of Email Validation Smart Constructor Source: https://fsprojects.github.io/FSharpPlus/type-validation Illustrates how to use the 'email' smart constructor with various inputs, showing examples of successful validation and different types of validation failures. The comments indicate the expected 'Success' or 'Failure' results, demonstrating the utility of the validation functions. ```F# // ***** Example usage ***** let success = email "bob@gmail.com" // Success (Email "bob@gmail.com") let failureAt = email "bobgmail.com" // Failure [MustContainAt] let failurePeriod = email "bob@gmailcom" // Failure [MustContainPeriod] let failureAll = email "" // Failure [MustNotBeEmpty;MustContainAt;MustContainPeriod] ``` -------------------------------- ### F# Main Web Application Logic and Routing Source: https://fsprojects.github.io/FSharpPlus/abstraction-monad The `app` function orchestrates the entire web application. It takes an `IDb` instance and defines two main routes: `overview` (GET /notes) and `register` (POST /note). Both routes use the `authenticated` middleware. The `choice` function combines multiple `WebPart`s, acting as a router. This snippet showcases the composition of filters, authentication, monadic computations (`monad { ... }`), and response generation using the previously defined modules. ```F# let app (db: IDb) = let overview = GET >=> (authenticated <| fun ctx userId -> monad { let! res = lift (db.getUserNotes userId) let ovm = toJson { myNotes = res.notes } return! OK ovm ctx }) let register = POST >=> (authenticated <| fun ctx userId -> monad { match ctx.request |> Request.tryGet "text" with | Ok text -> let! newNote = lift (db.addUserNote userId text) let rvm = toJson newNote return! OK rvm ctx | Error msg -> return! BAD_REQUEST msg ctx }) choice [ path "/" >=> (OK "/") path "/note" >=> register path "/notes" >=> overview ] ``` -------------------------------- ### F# Example Val Declarations Source: https://fsprojects.github.io/FSharpPlus/lens Declarations of example `val`s, `rayuela` of type `Book` and `authorName1` of type `string`, demonstrating the use of defined types in F#. ```F# val rayuela: Book val authorName1: string ``` -------------------------------- ### FSharpPlus.Data.Compose Module API Documentation Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-data-compose Documents the basic operations available in the Compose module, part of the FSharpPlus.Data namespace. It details functions like `run`, including their full usage, parameters, and return types. ```APIDOC Module: Compose Namespace: FSharpPlus.Data Assembly: FSharpPlus.dll Description: Basic operations on Compose Functions and values: Compose.run Full Usage: Compose.run arg1 Parameters: arg0: Compose<'a> Returns: 'a ``` -------------------------------- ### MapAsApplicative Module and Example Map Declarations Source: https://fsprojects.github.io/FSharpPlus/applicative-functors The 'MapAsApplicative' module from 'Applicative-functors' likely provides applicative operations for maps. It includes example map declarations 'r31' and 'r32'. ```APIDOC module MapAsApplicative from Applicative-functors val r31: Map<char,int> val r32: Map<char,int> ``` -------------------------------- ### API Documentation for FSharpPlus Functions Source: https://fsprojects.github.io/FSharpPlus/abstraction-applicative Detailed API documentation for key functions in FSharpPlus, including their signatures, summaries, and category information. ```APIDOC val map: f: ('T -> 'U) -> x: 'Functor<'T> -> 'Functor<'U> (requires member Map) *<summary>Lifts a function into a Functor.</summary> <category index="1">Functor</category>* ``` ```APIDOC val tryParse: value: string -> 'T option (requires member TryParse) *<summary> Converts to a value from its string representation. Returns None if the convertion doesn't succeed. </summary> <category index="21">Converter</category>* ``` ```APIDOC val option: f: ('g -> 'h) -> n: 'h -> _arg1: 'g option -> 'h *<summary> Takes a function, a default value and a option value. If the option value is None, the function returns the default value. Otherwise, it applies the function to the value inside Some and returns the result. </summary> <category index="0">Common Combinators</category>* ``` ```APIDOC val result: x: 'T -> 'Functor<'T> (requires member Return) *<summary> Lifts a value into a Functor. Same as return in Computation Expressions. </summary> <category index="2">Applicative</category>* ``` ```APIDOC val tryHead: source: 'Foldable<'T> -> 'T option (requires member TryHead) *<summary>Gets the first element of the foldable, or <c>None</c> if the foldable is empty.</summary> <category index="11">Foldable</category> <param name="source">The input foldable.</param> <returns>The first element of the foldable or None.</returns>* ``` ```APIDOC val lift2: f: ('T -> 'U -> 'V) -> x: 'Applicative<'T> -> y: 'Applicative<'U> -> 'Applicative<'V> (requires member Lift2) *<summary> Applies 2 lifted arguments to a non-lifted function. Equivalent to map2 in non list-like types. </summary> <category index="2">Applicative</category>* ``` -------------------------------- ### Get Value Dependent on State (gets) Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-operators Retrieves a value that is derived from the current state within a MonadState. It takes a function `f` to transform the state into the desired value. ```APIDOC gets: Full Usage: gets f Parameters: f: 'S -> 'T Returns: ^MonadState<'S,'T> Modifiers: inline Description: Gets a value which depends on the current state. ``` -------------------------------- ### System.Uri Class API Reference Source: https://fsprojects.github.io/FSharpPlus/type-seqt This section provides API documentation for the System.Uri class, outlining its constructor overloads, implemented interfaces, and key methods. It details functionalities for comparing URIs, extracting components, generating hash codes, and determining relative paths, essential for URI manipulation. ```APIDOC val uri: System.Uri Multiple items type Uri = interface ISerializable new: uriString: string -> unit + 6 overloads member Equals: comparand: obj -> bool member GetComponents: components: UriComponents * format: UriFormat -> string member GetHashCode: unit -> int member GetLeftPart: part: UriPartial -> string member IsBaseOf: uri: Uri -> bool member IsWellFormedOriginalString: unit -> bool member MakeRelative: toUri: Uri -> string ``` -------------------------------- ### F# DList Basic Operations Example Source: https://fsprojects.github.io/FSharpPlus/type-dlist Demonstrates how to use the `DList.length` and `DList.head` functions, both directly and via implicit module opening, to retrieve the length and first element of a DList instance in F#. ```F# let lengthOfList3 = DList.length list3 let lengthOfList3' = length list3 let headOf3 = DList.head list3 let headOf3' = head list3 ``` -------------------------------- ### Bitraverse.Bitraverse Method Overloads Source: https://fsprojects.github.io/FSharpPlus/reference/fsharpplus-control-bitraverse Comprehensive API documentation for the static `Bitraverse.Bitraverse` method, showcasing its multiple overloads designed for various bitraversal scenarios. Each entry specifies the full usage signature, parameters with their types, return types, and applicable modifiers, including type parameters where relevant. ```APIDOC Bitraverse.Bitraverse(arg1, arg2, arg3, arg4) Parameters: arg0: 't arg1: 'a arg2: 'b arg3: Default1 Returns: 'c -> 'c Modifiers: inline Bitraverse.Bitraverse(x, f, g, _impl) Parameters: x: ^Bitraversable<'T1,'U1> f: 'T1 -> 'Functor<'T2> g: 'U1 -> 'Functor<'U2> _impl: Default1 Returns: 'Functor<'Bitraversable<'T2,'U2>> Modifiers: inline Type parameters: ^Bitraversable<'T1,'U1>, 'T1, 'Functor<'T2>, 'U1, 'Functor<'U2>, 'Functor<'Bitraversable<'T2,'U2>> Bitraverse.Bitraverse(x, f, g, _impl) Parameters: x: ^Bitraversable<'T1,'U1> f: 'T1 -> 'Functor<'T2> g: 'U1 -> 'Functor<'U2> _impl: Default2 Returns: 'Functor<'Bitraversable<'T2,'U2>> Modifiers: inline Bitraverse.Bitraverse(arg1, f, g, _impl) Parameters: arg0: 'T1 * 'U1 f: 'T1 -> ^Functor<'T2> g: 'U1 -> ^Functor<'U2> _impl: Bitraverse Returns: ^Functor Modifiers: inline Type parameters: 'T1, 'U1, ^Functor<'T2>, ^Functor<'U2>, ^Functor<struct ('T2 * 'U2)>, 'T, 'U Bitraverse.Bitraverse(arg1, f, g, _impl) Parameters: arg0: 'T1 * 'U1 f: 'T1 -> ^Functor<'T2> g: 'U1 -> ^Functor<'U2> _impl: Bitraverse Returns: ^Functor<'T2*'U2> Modifiers: inline Bitraverse.Bitraverse(x, f, g, _impl) Parameters: x: Choice<'T1, 'Error1> f: 'Error1 -> ^Functor<'Error2> g: 'T1 -> ^Functor<'T2> _impl: Bitraverse Returns: ^Functor> Modifiers: inline Type parameters: 'T1, 'Error1, ^Functor<'Error2>, ^Functor<Choice<'Error2,'T2>>, ^Functor<'T2>, 'Error2, 'T2 Bitraverse.Bitraverse(x, f, g, _impl) Parameters: x: Result<'T1, 'Error1> f: 'Error1 -> ^Functor<'Error2> g: 'T1 -> ^Functor<'T2> _impl: Bitraverse Returns: ^Functor> Modifiers: inline Type parameters: 'T1, 'Error1, ^Functor<'Error2>, ^Functor<Result<'Error2,'T2>>, ^Functor<'T2>, 'Error2, 'T2 ```