FSharp.Core Gets the name of the method on the builder to use to construct the collection. This should match the metadata name of the target method. For example, this might be ".ctor" if targeting the type's constructor. Gets the type of the builder to use to construct the collection. Initialize the attribute to refer to the method on the type. The type of the builder to use to construct the collection. The name of the method on the builder to use to construct the collection. must refer to a static method that accepts a single parameter of type and returns an instance of the collection being built containing a copy of the data from that span. In future releases of .NET, additional patterns may be supported. Specifies the types of members that are dynamically accessed. This enumeration has a attribute that allows a bitwise combination of its member values. An abbreviation for the CLI type See the module for further operations related to sequences. See also F# Language Guide - Sequences. An abbreviation for the CLI type The type of immutable singly-linked lists. See the module for further operations related to lists. Use the constructors [] and :: (infix) to create values of this type, or the notation [1; 2; 3]. Use the values in the List module to manipulate values of this type, or pattern match against the values directly. See also F# Language Guide - Lists. Gets the tail of the list, which is a list containing all the elements of the list, excluding the first element Gets the number of items contained in the list Gets the element of the list at the given position. Lists are represented as linked lists so this is an O(n) operation. The index. The value at the given index. Gets a value indicating if the list contains no entries Gets the first element of the list Returns an empty list of a particular type Gets a slice of the list, the elements of the list from the given start index to the given end index. The start index. The end index. The sub list specified by the input indices. Get the index for the element offset elements away from the end of the collection. The rank of the index. The offset from the end. The corresponding index from the start. Returns a list with head as its first element and tail as its subsequent elements A new head value for the list. The existing list. The list with head appended to the front of tail. The type of immutable singly-linked lists. Use the constructors [] and :: (infix) to create values of this type, or the notation [1;2;3]. Use the values in the List module to manipulate values of this type, or pattern match against the values directly. All the values in the map, including the duplicates. The sequence will be ordered by the keys of the map. let sample = Map [ (1, "a"); (2, "b") ] sample.Values // evaluates to seq ["a"; "b"] The keys in the map. The sequence will be ordered by the keys of the map. let sample = Map [ (1, "a"); (2, "b") ] sample.Keys // evaluates to seq [1; 2] Lookup an element in the map. Raise KeyNotFoundException if no binding exists in the map. The input key. Thrown when the key is not found. The value mapped to the key. let sample = Map [ (1, "a"); (2, "b") ] sample.[1] // evaluates to "a" sample.[3] // throws KeyNotFoundException Returns true if there are no bindings in the map. let emptyMap: Map<int, string> = Map.empty emptyMap.IsEmpty // evaluates to true let notEmptyMap = Map [ (1, "a"); (2, "b") ] notEmptyMap.IsEmpty // evaluates to false The number of bindings in the map. let sample = Map [ (1, "a"); (2, "b") ] sample.Count // evaluates to 2 Lookup an element in the map, assigning to value if the element is in the domain of the map and returning false if not. The input key. A reference to the output value. true if the value is present, false if not. let sample = Map [ (1, "a"); (2, "b") ] sample.TryGetValue 1 // evaluates to (true, "a") sample.TryGetValue 3 // evaluates to (false, null) let mutable x = "" sample.TryGetValue (1, &x) // evaluates to true, x set to "a" let mutable y = "" sample.TryGetValue (3, &y) // evaluates to false, y unchanged Lookup an element in the map, returning a Some value if the element is in the domain of the map and None if not. The input key. The mapped value, or None if the key is not in the map. let sample = Map [ (1, "a"); (2, "b") ] sample.TryFind 1 // evaluates to Some "a" sample.TryFind 3 // evaluates to None Removes an element from the domain of the map. No exception is raised if the element is not present. The input key. The resulting map. let sample = Map [ (1, "a"); (2, "b") ] sample.Remove 1 // evaluates to map [(2, "b")] sample.Remove 3 // equal to sample Tests if an element is in the domain of the map. The input key. True if the map contains the given key. let sample = Map [ (1, "a"); (2, "b") ] sample.ContainsKey 1 // evaluates to true sample.ContainsKey 3 // evaluates to false Returns a new map with the value stored under key changed according to f. The input key. The change function. The resulting map. let sample = Map [ (1, "a"); (2, "b") ] let f x = match x with | Some s -> Some (s + "z") | None -> None sample.Change (1, f) // evaluates to map [(1, "az"); (2, "b")] Returns a new map with the binding added to the given map. If a binding with the given key already exists in the input map, the existing binding is replaced by the new binding in the result map. The key to add. The value to add. The resulting map. let sample = Map [ (1, "a"); (2, "b") ] sample.Add (3, "c") // evaluates to map [(1, "a"); (2, "b"); (3, "c")] sample.Add (2, "aa") // evaluates to map [(1, "a"); (2, "aa")] Builds a map that contains the bindings of the given IEnumerable. The input sequence of key/value pairs. The resulting map. Map [ (1, "a"); (2, "b") ] // evaluates to map [(1, "a"); (2, "b")] Immutable maps based on binary trees, where keys are ordered by F# generic comparison. By default comparison is the F# structural comparison function or uses implementations of the IComparable interface on key values. See the module for further operations on maps. All members of this class are thread-safe and may be used concurrently from multiple threads. Returns a new set with the elements of the second set removed from the first. The first input set. The second input set. A set containing elements of the first set that are not contained in the second set. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(2).Add(3).Add(4) printfn $"The new set is: {set1 - set2}" The sample evaluates to the following output: The new set is: set [1] Compute the union of the two sets. The first input set. The second input set. The union of the two input sets. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(2).Add(3).Add(4) printfn $"Output is %A" {set1 + set2}" The sample evaluates to the following output: The new set is: set [1; 2; 3; 4] Returns the lowest element in the set according to the ordering being used for the set. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"MinimumElement: {set.MinimumElement}" The sample evaluates to the following output: MinimumElement: 1 Returns the highest element in the set according to the ordering being used for the set. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"MaximumElement: {set.MaximumElement}" The sample evaluates to the following output: MaximumElement: 3 A useful shortcut for Set.isEmpty. See the Set module for further operations on sets. let set = Set.empty.Add(2).Add(3) printfn $"Is the set empty? {set.IsEmpty}" The sample evaluates to the following output: Is the set empty? false The number of elements in the set let set = Set.empty.Add(1).Add(1).Add(2) printfn $"The set has {set.Count} elements" The sample evaluates to the following output: The set has 3 elements A useful shortcut for Set.remove. Note this operation produces a new set and does not mutate the original set. The new set will share many storage nodes with the original. See the Set module for further operations on sets. The value to remove from the set. The result set. let set = Set.empty.Add(1).Add(1).Add(2) printfn $"The new set is: {set}" The sample evaluates to the following output: The new set is: set [2] Evaluates to "true" if all elements of the second set are in the first. The set to test against. True if this set is a superset of otherSet. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a superset of {set2}? {Set.isSuperset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a superset of set [1; 2; 3; 4]? false Evaluates to "true" if all elements of the first set are in the second. The set to test against. True if this set is a subset of otherSet. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a subset of {set2}? {Set.isSubset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a subset of set [1; 2; 3; 4]? true Evaluates to "true" if all elements of the second set are in the first, and at least one element of the first is not in the second. The set to test against. True if this set is a proper superset of otherSet. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a proper superset of {set2}? {Set.isProperSuperset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a proper superset of set [1; 2; 3; 4]? false Evaluates to "true" if all elements of the first set are in the second, and at least one element of the second is not in the first. The set to test against. True if this set is a proper subset of otherSet. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a proper superset of {set2}? {Set.isProperSuperset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a proper subset of set [1; 2; 3; 4]? true A useful shortcut for Set.contains. See the Set module for further operations on sets. The value to check. True if the set contains value. let set = Set.empty.Add(2).Add(3) printfn $"Does the set contain 1? {set.Contains(1)}" The sample evaluates to the following output: Does the set contain 1? false A useful shortcut for Set.add. Note this operation produces a new set and does not mutate the original set. The new set will share many storage nodes with the original. See the Set module for further operations on sets. The value to add to the set. The result set. let set = Set.empty.Add(1).Add(1).Add(2) printfn $"The new set is: {set}" The sample evaluates to the following output: The new set is: set [1; 2] Create a set containing elements drawn from the given sequence. The input sequence. The result set. let sequenceOfNumbers = seq { 1 .. 3 } let numbersInSet = Set(sequenceOfNumbers) printfn $"The set is {numbersInSet}" Creates a new Set containing the elements of the given sequence. set [1; 2; 3] Immutable sets based on binary trees, where elements are ordered by F# generic comparison. By default comparison is the F# structural comparison function or uses implementations of the IComparable interface on element values. See the module for further operations on sets. All members of this class are thread-safe and may be used concurrently from multiple threads. Fetches an element from a 2D array. You can also use the syntax array.[index1,index2]. The input array. The index along the first dimension. The index along the second dimension. The value of the array at the given index. Thrown when the indices are negative or exceed the bounds of the array. Indexer syntax is generally preferred, e.g. let array = array2D [ [ 1.0; 2.0 ]; [ 3.0; 4.0 ] ] array[0,1] Evaluates to 2.0. let array = array2D [ [ 1.0; 2.0 ]; [ 3.0; 4.0 ] ] Array2D.get array 0 1 Evaluates to 2.0. Sets the value of an element in an array. You can also use the syntax array.[index1,index2] <- value. The input array. The index along the first dimension. The index along the second dimension. The value to set in the array. Thrown when the indices are negative or exceed the bounds of the array. Indexer syntax is generally preferred, e.g. let array = Array2D.zeroCreate 2 2 array[0,1] <- 4.0 let array = Array2D.zeroCreate 2 2 Array2D.set array 0 1 4.0 After evaluation array is a 2x2 array with contents [[0.0; 4.0]; [0.0; 0.0]] Builds a new array whose elements are the same as the input array but where a non-zero-based input array generates a corresponding zero-based output array. The input array. The zero-based output array. let inputs = Array2D.createBased 1 1 2 3 1 inputs |> Array2D.rebase Evaluates to a 2x2 zero-based array with contents [[1; 1]; [1; 1]] Builds a new array whose elements are the results of applying the given function to each of the elements of the array. The integer indices passed to the function indicates the element being transformed. For non-zero-based arrays the basing on an input array will be propagated to the output array. A function that is applied to transform each element of the array. The two integers provide the index of the element. The input array. An array whose elements have been transformed by the given mapping. let inputs = array2D [ [ 3; 4 ]; [ 13; 14 ] ] inputs |> Array2D.mapi (fun i j v -> i + j + v) Evaluates to a 2x2 array with contents [[3; 5;]; [14; 16]] Builds a new array whose elements are the results of applying the given function to each of the elements of the array. For non-zero-based arrays the basing on an input array will be propagated to the output array. A function that is applied to transform each item of the input array. The input array. An array whose elements have been transformed by the given mapping. let inputs = array2D [ [ 3; 4 ]; [ 13; 14 ] ] inputs |> Array2D.map (fun v -> 2 * v) Evaluates to a 2x2 array with contents [[6; 8;]; [26; 28]] Returns the length of an array in the second dimension. The input array. The length of the array in the second dimension. let array = array2D [ [ 3; 4; 5 ]; [ 13; 14; 15 ] ] array |> Array2D.length2 Evaluates to 3. Returns the length of an array in the first dimension. The input array. The length of the array in the first dimension. let array = array2D [ [ 3; 4; 5 ]; [ 13; 14; 15 ] ] array |> Array2D.length1 Evaluates to 2. Applies the given function to each element of the array. The integer indices passed to the function indicates the index of element. A function to apply to each element of the array with the indices available as an argument. The input array. let inputs = array2D [ [ 3; 4 ]; [ 13; 14 ] ] inputs |> Array2D.iteri (fun i j v -> printfn $"value at ({i},{j}) = {v}") Evaluates to unit and prints value at (0,0) = 3 value at (0,1) = 4 value at (1,0) = 13 value at (1,1) = 14 in the console. Applies the given function to each element of the array. A function to apply to each element of the array. The input array. let inputs = array2D [ [ 3; 4 ]; [ 13; 14 ] ] inputs |> Array2D.iter (fun v -> printfn $"value = {v}") Evaluates to unit and prints value = 3 value = 4 value = 13 value = 14 in the console. Creates a based array where the entries are initially Unchecked.defaultof<'T>. The base for the first dimension of the array. The base for the second dimension of the array. The length of the first dimension of the array. The length of the second dimension of the array. The created array. Thrown when base1, base2, length1, or length2 is negative. Array2D.zeroCreateBased 1 1 2 3 Evaluates to a 2x3 1-based array with contents [[0; 0; 0]; [0; 0; 0]] Creates a based array whose elements are all initially the given value. The base for the first dimension of the array. The base for the second dimension of the array. The length of the first dimension of the array. The length of the second dimension of the array. The value to populate the new array. The created array. Thrown when base1, base2, length1, or length2 is negative. Array2D.createBased 1 1 2 3 1 Evaluates to a 2x3 1-based array with contents [[1; 1; 1]; [1; 1; 1]] Creates a based array given the dimensions and a generator function to compute the elements. The base for the first dimension of the array. The base for the second dimension of the array. The length of the first dimension of the array. The length of the second dimension of the array. A function to produce elements of the array given the two indices. The created array. Thrown when base1, base2, length1, or length2 is negative. Array2D.initBased 1 1 2 3 (fun i j -> i + j) Evaluates to a 2x3 1-based array with contents [[2; 3; 4]; [3; 4; 5]] Creates an array where the entries are initially Unchecked.defaultof<'T>. The length of the first dimension of the array. The length of the second dimension of the array. The created array. Thrown when length1 or length2 is negative. Array2D.zeroCreate 2 3 Evaluates to a 2x3 array with contents [[0; 0; 0]; [0; 0; 0]] Creates an array whose elements are all initially the given value. The length of the first dimension of the array. The length of the second dimension of the array. The value to populate the new array. The created array. Thrown when length1 or length2 is negative. Array2D.create 2 3 1 Evaluates to a 2x3 array with contents [[1; 1; 1]; [1; 1; 1]] Creates an array given the dimensions and a generator function to compute the elements. The length of the first dimension of the array. The length of the second dimension of the array. A function to produce elements of the array given the two indices. The generated array. Thrown when either of the lengths is negative. Array2D.init 2 3 (fun i j -> i + j) Evaluates to a 2x3 array with contents [[0; 1; 2]; [1; 2; 3]] Reads a range of elements from the first array and write them into the second. The source array. The first-dimension index to begin copying from in the source array. The second-dimension index to begin copying from in the source array. The target array. The first-dimension index to begin copying into in the target array. The second-dimension index to begin copying into in the target array. The number of elements to copy across the first dimension of the arrays. The number of elements to copy across the second dimension of the arrays. Thrown when any of the indices are negative or if either of the counts are larger than the dimensions of the array allow. Slicing syntax is generally preferred, e.g. let source = array2D [ [ 3; 4 ]; [ 13; 14 ] ] let target = array2D [ [ 2; 2; 2 ]; [ 12; 12; 12 ] ] target[0..1,1..2] <- source let source = array2D [ [ 3; 4 ]; [ 13; 14 ] ] let target = array2D [ [ 2; 2; 2 ]; [ 12; 12; 12 ] ] Array2D.blit source 0 0 target 0 1 2 2 After evaluation target contains [ [ 2; 3; 4 ]; [ 12; 13; 14 ] ]. Builds a new array whose elements are the same as the input array. For non-zero-based arrays the basing on an input array will be propagated to the output array. The input array. A copy of the input array. open System let array = Array2D.zeroCreate<int> 10 10 array |> Array2D.copy Evaluates to a new copy of the 10x10 array. Fetches the base-index for the second dimension of the array. The input array. The base-index of the second dimension of the array. Create a 10x10 1-based array: open System let array = Array.CreateInstance(typeof<int>, [| 10; 10 |], [| 1; 1 |]) :?> int[,] array |> Array2D.base2 Evaluates to 1. Fetches the base-index for the first dimension of the array. The input array. The base-index of the first dimension of the array. Create a 10x10 1-based array: open System let array = Array.CreateInstance(typeof<int>, [| 10; 10 |], [| 1; 1 |]) :?> int[,] array |> Array2D.base1 Evaluates to 1. Contains operations for working with 2-dimensional arrays. See also F# Language Guide - Arrays. F# and CLI multi-dimensional arrays are typically zero-based. However, CLI multi-dimensional arrays used in conjunction with external libraries (e.g. libraries associated with Visual Basic) be non-zero based, using a potentially different base for each dimension. The operations in this module will accept such arrays, and the basing on an input array will be propagated to a matching output array on the Array2D.map and Array2D.mapi operations. Non-zero-based arrays can also be created using Array2D.zeroCreateBased, Array2D.createBased and Array2D.initBased. Get an implementation of equality semantics using the given functions. A function to generate a hash code from a value. A function to test equality of two values. An object implementing using the given functions. Create a dictionary which uses the given functions for equality and hashing: open System.Collections.Generic let modIdentity = HashIdentity.FromFunctions((fun i -> i%5), (fun i1 i2 -> i1%5 = i2%5)) let dict = new Dictionary<int,int>(HashIdentity.FromFunctions) dict.[2] <- 6 dict.[7] <- 10 In this example, only one entry is added, as the keys 2 and 7 have the same hash and are equal according to the provided functions. Get an implementation of equality semantics using reference equality and reference hashing. An object implementing using and . Create a dictionary which uses reference equality and hashing on the key, giving each key reference identity: open System.Collections.Generic let dict = new Dictionary<int array,int>(HashIdentity.Structural) let arr1 = [| 1;2;3 |] let arr2 = [| 1;2;3 |] dict.Add(arr1, 6) dict.Add(arr2, 7) In this example, two entries are added to the dictionary, as the arrays have different object reference identity. Get an implementation of equality semantics using limited structural equality and structural hashing. The limit on the number of hashing operations used. An object implementing . Create a dictionary which uses limited structural equality and structural hashing on the key, allowing trees as efficient keys: open System.Collections.Generic type Tree = Tree of int * Tree list let dict = new Dictionary<Tree,int>(HashIdentity.LimitedStructural 4) let tree1 = Tree(0, []) let tree2 = Tree(0, [tree1; tree1]) dict.Add(tree1, 6) dict.Add(tree2, 7) Get an implementation of equality semantics using non-structural equality and non-structural hashing. An object implementing using and . Create a dictionary which uses non-structural equality and hashing on the key: open System.Collections.Generic let dict = new Dictionary<System.DateTime,int>(HashIdentity.NonStructural) dict.Add(System.DateTime.Now, 1) Get an implementation of equality semantics using structural equality and structural hashing. An object implementing using and . Create a dictionary which uses structural equality and structural hashing on the key, allowing an array as a key: open System.Collections.Generic let dict = new Dictionary<int array,int>(HashIdentity.Structural) let arr1 = [| 1;2;3 |] let arr2 = [| 1;2;3 |] dict.[arr1] <- 6 dict.[arr2] >- 7 In this example, only one entry is added to the dictionary, as the arrays identical by structural equality. Common notions of value identity implementing the interface, for constructing objects and other collections Get an implementation of comparison semantics using the given function. A function to compare two values. An object implementing using the supplied function. Create and use a comparer using the given function: let comparer = ComparisonIdentity.FromFunction(fun i1 i2 -> compare (i1%5) (i2%5)) comparer.Compare(7, 2) Evaluates to 0because 7 and 2 compare as equal using to the provided function. Get an implementation of comparison semantics using non-structural comparison. An object implementing using . Create and use a comparer using structural comparison: let comparer = ComparisonIdentity.NonStructural<System.DateTime> comparer.Compare(System.DateTime.Now, System.DateTime.Today) Evaluates to 1. Get an implementation of comparison semantics using structural comparison. An object implementing using . Create and use a comparer using structural comparison: let compareTuples = ComparisonIdentity.Structural<int * int> compareTuples.Compare((1, 4), (1, 5)) Evaluates to -1. Common notions of value ordering implementing the interface, for constructing sorted data structures and performing sorting operations. Returns a random sample of elements from the given sequence with the specified randomizer function, each element can be selected only once. The randomizer function, must return a float number from [0.0..1.0) range. The number of elements to return. The input sequence. A sequence of randomly selected elements from the input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input sequence. Thrown when the randomizer function returns a number outside the range [0.0..1.0). let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomSampleBy Random.Shared.NextDouble 3 Can evaluate to seq { 3; 1; 2 }. Returns a random sample of elements from the given sequence with the specified Random instance, each element can be selected only once. The Random instance. The number of elements to return. The input sequence. A sequence of randomly selected elements from the input sequence. Thrown when the input sequence is null. Thrown when the random argument is null. Thrown when the input sequence is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input sequence. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomSampleWith Random.Shared 3 Can evaluate to seq { 3; 1; 2 }. Returns a random sample of elements from the given sequence, each element can be selected only once. The number of elements to return. The input sequence. A sequence of randomly selected elements from the input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input sequence. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomSample 3 Can evaluate to seq { 3; 1; 2 }. Returns a sequence of random elements from the given sequence with the specified randomizer function, each element can be selected multiple times. The randomizer function, must return a float number from [0.0..1.0) range. The number of elements to return. The input sequence. A sequence of randomly selected elements from the input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. Thrown when count is less than 0. Thrown when the randomizer function returns a number outside the range [0.0..1.0). let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomChoicesBy Random.Shared.NextDouble 3 Can evaluate to seq { 3; 1; 3 }. Returns a sequence of random elements from the given sequence with the specified Random instance, each element can be selected multiple times. The Random instance. The number of elements to return. The input sequence. A sequence of randomly selected elements from the input sequence. Thrown when the input sequence is null. Thrown when the random argument is null. Thrown when the input sequence is empty. Thrown when count is less than 0. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomChoicesWith Random.Shared 3 Can evaluate to seq { 3; 1; 3 }. Returns an sequence of random elements from the given sequence, each element can be selected multiple times. The number of elements to return. The input sequence. A sequence of randomly selected elements from the input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. Thrown when count is less than 0. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomChoices 3 Can evaluate to seq { 3; 1; 3 }. Returns a random element from the given sequence with the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The input sequence. A randomly selected element from the input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. Thrown when the randomizer function returns a number outside the range [0.0..1.0). let inputs = seq { 0; 1; 2; 3; 4 } let randomizer = Random.Shared.NextDouble inputs |> Seq.randomChoiceBy randomizer Can evaluate to 3. Returns a random element from the given sequence with the specified Random instance. The Random instance. The input sequence. A randomly selected element from the input array. Thrown when the input sequence is null. Thrown when the random argument is null. Thrown when the input sequence is empty. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomChoiceWith Random.Shared Can evaluate to 3. Returns a random element from the given sequence. The input sequence. A randomly selected element from the input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomChoice Can evaluate to 3. Return a new sequence shuffled in a random order with the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when the randomizer function returns a number outside the range [0.0..1.0). let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomShuffleBy Random.Shared.NextDouble Can evaluate to seq { 0; 2; 4; 3; 1 }. Return a new sequence shuffled in a random order with the specified Random instance. The Random instance. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when the random argument is null. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomShuffleWith Random.Shared Can evaluate to seq { 0; 2; 4; 3; 1 }. Return a new sequence shuffled in a random order. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = seq { 0; 1; 2; 3; 4 } inputs |> Seq.randomShuffle Can evaluate to seq { 0; 2; 4; 3; 1 }. Return a new sequence with new items inserted before the given index. The index where the items should be inserted. The values to insert. The input sequence. The result sequence. Thrown when index is below 0 or greater than source.Length. seq { 0; 1; 2 } |> Seq.insertManyAt 1 [8; 9] Evaluates to a sequence yielding the same results as seq { 0; 8; 9; 1; 2 }. Return a new sequence with a new item inserted before the given index. The index where the item should be inserted. The value to insert. The input sequence. The result sequence. Thrown when index is below 0 or greater than source.Length. seq { 0; 1; 2 } |> Seq.insertAt 1 9 Evaluates to a sequence yielding the same results as seq { 0; 9; 1; 2 }. Return a new sequence with the item at a given index set to the new value. The index of the item to be replaced. The new value. The input sequence. The result sequence. Thrown when index is outside 0..source.Length - 1 seq { 0; 1; 2 } |> Seq.updateAt 1 9 Evaluates to a sequence yielding the same results as seq { 0; 9; 2 }. Return a new sequence with the number of items starting at a given index removed. The index of the item to be removed. The number of items to remove. The input sequence. The result sequence. Thrown when index is outside 0..source.Length - count seq { 0; 1; 2; 3 } |> Seq.removeManyAt 1 2 Evaluates to a sequence yielding the same results as seq { 0; 3 }. Return a new sequence with the item at a given index removed. The index of the item to be removed. The input sequence. The result sequence. Thrown when index is outside 0..source.Length - 1 seq { 0; 1; 2 } |> Seq.removeAt 1 Evaluates to a sequence yielding the same results as seq { 0; 2 }. Combines the three sequences into a sequence of triples. The sequences need not have equal lengths: when one sequence is exhausted any remaining elements in the other sequences are ignored. The first input sequence. The second input sequence. The third input sequence. The result sequence. Thrown when any of the input sequences is null. let numbers = [1; 2] let names = ["one"; "two"] let roman = ["I"; "II"] Seq.zip3 numbers names roman Evaluates to a sequence yielding the same results as seq { (1, "one", "I"); (2, "two", "II") }. Combines the two sequences into a sequence of pairs. The two sequences need not have equal lengths: when one sequence is exhausted any remaining elements in the other sequence are ignored. The first input sequence. The second input sequence. The result sequence. Thrown when either of the input sequences is null. let numbers = [1; 2] let names = ["one"; "two"] Seq.zip numbers names Evaluates to a sequence yielding the same results as seq { (1, "one"); (2, "two") }. Returns a sequence yielding sliding windows containing elements drawn from the input sequence. Each window is returned as a fresh array. The number of elements in each window. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when windowSize is not positive. let inputs = [1; 2; 3; 4; 5] inputs |> Seq.windowed 3 Evaluates to a sequence of arrays yielding the results seq { [| 1; 2; 3 |]; [| 2; 3; 4 |]; [| 3; 4; 5 |] } Returns a sequence that contains the elements generated by the given computation. The given initial state argument is passed to the element generator. For each IEnumerator elements in the stream are generated on-demand by applying the element generator, until a None value is returned by the element generator. Each call to the element generator returns a new residual state. The stream will be recomputed each time an IEnumerator is requested and iterated for the Seq. A function that takes in the current state and returns an option tuple of the next element of the sequence and the next state value. The initial state value. The result sequence. 1 |> Seq.unfold (fun state -> if state > 100 then None else Some (state, state * 2)) Evaluates to a sequence yielding the same results as seq { 1; 2; 4; 8; 16; 32; 64 } 1I |> Seq.unfold (fun state -> Some (state, state * 2I)) Evaluates to an infinite sequence yielding the results seq { 1I; 2I; 4I; 8I; ... } Returns a sequence that when enumerated returns at most N elements. The maximum number of items to enumerate. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.truncate 2 Evaluates to a sequence yielding the same results as seq { "a"; "b" } let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.truncate 6 Evaluates to a sequence yielding the same results as seq { "a"; "b"; "c"; "d" } let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.truncate 0 Evaluates to the empty sequence. Returns the transpose of the given sequence of sequences. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The input sequence. The transposed sequence. Thrown when the input sequence is null. let inputs = [ [ 10; 20; 30 ] [ 11; 21; 31 ] ] inputs |> Seq.transpose Evaluates to a sequence of sequences yielding the same results as [ [10; 11]; [20; 21]; [30; 31] ]. Applies the given function to successive elements, returning the first result where the function returns "Some(x)". A function that transforms items from the input sequence into options. The input sequence. The chosen element or None. Thrown when the input sequence is null. let input = [1; 2; 3] input |> Seq.tryPick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to Some "2". let input = [1; 2; 3] input |> Seq.tryPick (fun n -> if n > 3 = 0 then Some (string n) else None) Evaluates to None. Returns the index of the last element in the sequence that satisfies the given predicate. Return None if no such element exists. This function digests the whole initial sequence as soon as it is called. As a result this function should not be used with large or infinite sequences. A function that evaluates to a Boolean when given an item in the sequence. The input sequence. The found index or None. Thrown when the input sequence is null. Try to find the index of the first even number from the back: let inputs = [1; 2; 3; 4; 5] inputs |> Seq.tryFindIndexBack (fun elm -> elm % 2 = 0) Evaluates to Some 3 Try to find the index of the first even number from the back: let inputs = [1; 3; 5; 7] inputs |> Seq.tryFindIndexBack (fun elm -> elm % 2 = 0) Evaluates to None Tries to find the nth element in the sequence. Returns None if index is negative or the input sequence does not contain enough elements. The index of element to retrieve. The input sequence. The nth element of the sequence or None. Thrown when the input sequence is null. let inputs = ["a"; "b"; "c"] inputs |> Seq.tryItem 1 Evaluates to Some "b". let inputs = ["a"; "b"; "c"] inputs |> Seq.tryItem 4 Evaluates to None. Returns the index of the first element in the sequence that satisfies the given predicate. Return None if no such element exists. A function that evaluates to a Boolean when given an item in the sequence. The input sequence. The found index or None. Thrown when the input sequence is null. Try to find the index of the first even number: let inputs = [1; 2; 3; 4; 5] inputs |> Seq.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to Some 1 Try to find the index of the first even number: let inputs = [1; 3; 5; 7] inputs |> Seq.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to None Returns the last element for which the given function returns True. Return None if no such element exists. This function digests the whole initial sequence as soon as it is called. As a result this function should not be used with large or infinite sequences. A function that evaluates to a Boolean when given an item in the sequence. The input sequence. The found element or None. Thrown when the input sequence is null. Try to find the first even number from the back: let inputs = [1; 2; 3; 4; 5] inputs |> Seq.tryFindBack (fun elm -> elm % 2 = 0) Evaluates to Some 4 Try to find the first even number from the back: let inputs = [1; 5; 3] inputs |> Seq.tryFindBack (fun elm -> elm % 2 = 0) Evaluates to None Returns the first element for which the given function returns True. Return None if no such element exists. A function that evaluates to a Boolean when given an item in the sequence. The input sequence. The found element or None. Thrown when the input sequence is null. Try to find the first even number: let inputs = [1; 2; 3] inputs |> Seq.tryFind (fun elm -> elm % 2 = 0) Evaluates to Some 2 Try to find the first even number: let inputs = [1; 5; 3] inputs |> Seq.tryFind (fun elm -> elm % 2 = 0) Evaluates to None Builds a list from the given collection. The input sequence. The result list. Thrown when the input sequence is null. let inputs = seq { 1; 2; 5 } inputs |> Seq.toList Evaluates to [ 1; 2; 5 ]. Builds an array from the given collection. The input sequence. The result array. Thrown when the input sequence is null. let inputs = seq { 1; 2; 5 } inputs |> Seq.toArray Evaluates to [| 1; 2; 5 |]. Returns a sequence that, when iterated, yields elements of the underlying sequence while the given predicate returns True, and then returns no further elements. A function that evaluates to false when no more items should be returned. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = ["a"; "bb"; "ccc"; "d"] inputs |> Seq.takeWhile (fun x -> x.Length < 3) Evaluates to a sequence yielding the same results as seq { "a"; "bb" } Returns the first N elements of the sequence. Throws InvalidOperationException if the count exceeds the number of elements in the sequence. Seq.truncate returns as many items as the sequence contains instead of throwing an exception. The number of items to take. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty and the count is greater than zero. Thrown when count exceeds the number of elements in the sequence. let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.take 2 Evaluates to a sequence yielding the same results as ["a"; "b"] let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.take 6 Throws InvalidOperationException. let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.take 0 Evaluates to a sequence yielding no results. Returns a sequence that skips 1 element of the underlying sequence and then yields the remaining elements of the sequence. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. let inputs = ["a"; "bb"; "ccc"] inputs |> Seq.tail Evaluates to a sequence yielding the same results as seq { "bb"; "ccc" } Returns the sum of the results generated by applying the function to each element of the sequence. The generated elements are summed using the + operator and Zero property associated with the generated type. A function to transform items from the input sequence into the type that will be summed. The input sequence. The computed sum. let input = [ "aa"; "bbb"; "cc" ] input |> Seq.sumBy (fun s -> s.Length) Evaluates to 7. Returns the sum of the elements in the sequence. The elements are summed using the + operator and Zero property associated with the generated type. The input sequence. The computed sum. let input = [ 1; 5; 3; 2 ] input |> Seq.sum Evaluates to 11. Applies a key-generating function to each element of a sequence and yield a sequence ordered descending by keys. The keys are compared using generic comparison as implemented by . This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence. This is a stable sort, that is the original order of equal elements is preserved. A function to transform items of the input sequence into comparable keys. The input sequence. The result sequence. Thrown when the input sequence is null. let input = ["a"; "bbb"; "cccc"; "dd"] input |> Seq.sortByDescending (fun s -> s.Length) Evaluates to a sequence yielding the same results as seq { "cccc"; "bbb"; "dd"; "a" }. Yields a sequence ordered descending by keys. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence. This is a stable sort, that is the original order of equal elements is preserved. The input sequence. The result sequence. Thrown when the input sequence is null. let input = seq { 8; 4; 3; 1; 6; 1 } input |> Seq.sortDescending Evaluates to a sequence yielding the same results as seq { 8; 6; 4; 3; 1; 1 }. Applies a key-generating function to each element of a sequence and yield a sequence ordered by keys. The keys are compared using generic comparison as implemented by . This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence and uses a stable sort, that is the original order of equal elements is preserved. A function to transform items of the input sequence into comparable keys. The input sequence. The result sequence. Thrown when the input sequence is null. let input = [ "a"; "bbb"; "cccc"; "dd" ] input |> Seq.sortBy (fun s -> s.Length) Evaluates to a sequence yielding the same results as seq { "a"; "dd"; "bbb"; "cccc" }. Yields a sequence ordered using the given comparison function. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence and uses a stable sort, that is the original order of equal elements is preserved. The function to compare the collection elements. The input sequence. The result sequence. Sort a sequence of pairs using a comparison function that compares string lengths then index numbers: let compareEntries (n1: int, s1: string) (n2: int, s2: string) = let c = compare s1.Length s2.Length if c <> 0 then c else compare n1 n2 let input = [ (0,"aa"); (1,"bbb"); (2,"cc"); (3,"dd") ] input |> Seq.sortWith compareEntries Evaluates to a sequence yielding the same results as seq { (0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb") }. Yields a sequence ordered by keys. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence and uses a stable sort, that is the original order of equal elements is preserved. The input sequence. The result sequence. Thrown when the input sequence is null. let input = seq { 8; 4; 3; 1; 6; 1 } Seq.sort input Evaluates to a sequence yielding the same results as seq { 1; 1 3; 4; 6; 8 }. Returns a sequence that, when iterated, skips elements of the underlying sequence while the given predicate returns True, and then yields the remaining elements of the sequence. A function that evaluates an element of the sequence to a boolean value. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = seq { "a"; "bbb"; "cc"; "d" } inputs |> Seq.skipWhile (fun x -> x.Length < 3) Evaluates a sequence yielding the same results as seq { "bbb"; "cc"; "d" } Returns a sequence that skips N elements of the underlying sequence and then yields the remaining elements of the sequence. The number of items to skip. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when count exceeds the number of elements in the sequence. let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.skip 2 Evaluates a sequence yielding the same results as seq { "c"; "d" } let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.skip 5 Throws ArgumentException. let inputs = ["a"; "b"; "c"; "d"] inputs |> Seq.skip -1 Evaluates a sequence yielding the same results as seq { "a"; "b"; "c"; "d" }. Returns a sequence yielding one item only. The input item. The result sequence of one item. Seq.singleton 7 Evaluates to a sequence yielding the same results as seq { 7 }. Like foldBack, but returns the sequence of intermediary and final results. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. A function that updates the state with each element from the sequence. The input sequence. The initial state. The resulting sequence of computed states. Thrown when the input sequence is null. Apply a list charges from back to front, and collect the running balances as each is applied: type Charge = | In of int | Out of int let inputs = [ In 1; Out 2; In 3 ] (inputs, 0) ||> Seq.scanBack (fun charge acc -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to a sequence yielding the same results as seq { 2; 1; 3; 0 } by processing each input from back to front. Note 0 is the initial state, 3 the next state, 1 the next state, and 2 the final state, and the states are produced from back to front. Like fold, but computes on-demand and returns the sequence of intermediary and final results. A function that updates the state with each element from the sequence. The initial state. The input sequence. The resulting sequence of computed states. Thrown when the input sequence is null. Apply a list charges and collect the running balances as each is applied: type Charge = | In of int | Out of int let inputs = seq { In 1; Out 2; In 3 } (0, inputs) ||> Seq.scan (fun acc charge -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to a sequence yielding the same results as seq { 0; 1; -1; 2 }. Note 0 is the initial state, 1 the next state, -1 the next state, and 2 the final state. Returns a new sequence with the elements in reverse order. The input sequence. The reversed sequence. Thrown when the input sequence is null. This function consumes the whole input sequence before yielding the first element of the reversed sequence. let input = seq { 0; 1; 2 } input |> Seq.rev Evaluates to a sequence yielding the same results as seq { 2; 1; 0 }. Applies a function to each element of the sequence, starting from the end, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f i0 (...(f iN-1 iN)). A function that takes in the next-to-last element of the sequence and the current accumulated result to produce the next accumulated result. The input sequence. The final result of the reductions. Thrown when the input sequence is null. Thrown when the input sequence is empty. This function consumes the whole input sequence before returning the result. let inputs = [1; 3; 4; 2] inputs |> Seq.reduceBack (fun a b -> a + b * 10) Evaluates to 2431, by computing 1 + (3 + (4 + 2 * 10) * 10) * 10 Creates a sequence by replicating the given initial value. The number of elements to replicate. The value to replicate The generated sequence. Seq.replicate 3 "a" Evaluates to a sequence yielding the same results as seq { "a"; "a"; "a" }. Applies a function to each element of the sequence, threading an accumulator argument through the computation. Begin by applying the function to the first two elements. Then feed this result into the function along with the third element and so on. Return the final result. A function that takes in the current accumulated result and the next element of the sequence to produce the next accumulated result. The input sequence. The final result of the reduction function. Thrown when the input sequence is null. Thrown when the input sequence is empty. let inputs = [1; 3; 4; 2] inputs |> Seq.reduce (fun a b -> a * 10 + b) Evaluates to 1342, by computing ((1 * 10 + 3) * 10 + 4) * 10 + 2 Builds a new sequence object that delegates to the given sequence object. This ensures the original sequence cannot be rediscovered and mutated by a type cast. For example, if given an array the returned sequence will return the elements of the array, but you cannot cast the returned sequence object to an array. The input sequence. The result sequence. Thrown when the input sequence is null. let input = [| 1; 2; 3 |] input |> Seq.readonly Evaluates to a sequence yielding the same results as seq { 1; 2; 3 }. let input = [| 1; 2; 3 |] let readonlyView = input |> Seq.readonly (readonlyView :?> int array).[1] <- 4 Throws an InvalidCastException. Applies the given function to successive elements, returning the first x where the function returns "Some(x)". A function to transform each item of the input sequence into an option of the output type. The input sequence. The selected element. Thrown when the input sequence is null. Thrown when every item of the sequence evaluates to None when the given function is applied. let input = [1; 2; 3] input |> Seq.pick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to "2". let input = [1; 2; 3] input |> Seq.pick (fun n -> if n > 3 = 0 then Some (string n) else None) Throws KeyNotFoundException. Returns a sequence with all elements permuted according to the specified permutation. This function consumes the whole input sequence before yielding the first element of the result sequence. The function that maps input indices to output indices. The input sequence. The result sequence. Thrown when the input sequence is null. Thrown when indexMap does not produce a valid permutation. let inputs = [1; 2; 3; 4] inputs |> Seq.permute (fun x -> (x + 1) % 4) Evaluates to a sequence yielding the same results as seq { 4; 1; 2; 3 }. Returns a sequence of each element in the input sequence and its predecessor, with the exception of the first element which is only returned as the predecessor of the second element. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = seq { 1; 2; 3; 4 } inputs |> Seq.pairwise Evaluates to a sequence yielding the same results as seq { (1, 2); (2, 3); (3, 4) }. Views the given list as a sequence. The input list. The result sequence. let inputs = [ 1; 2; 5 ] inputs |> Seq.ofList Evaluates to a sequence yielding the same results as seq { 1; 2; 5 }. Views the given array as a sequence. The input array. The result sequence. Thrown when the input sequence is null. let inputs = [| 1; 2; 5 |] inputs |> Seq.ofArray Evaluates to a sequence yielding the same results as seq { 1; 2; 5 }. Computes the nth element in the collection. The index of element to retrieve. The input sequence. The nth element of the sequence. Thrown when the input sequence is null. Thrown when the index is negative or the input sequence does not contain enough elements. Returns the lowest of all elements of the sequence, compared via Operators.min on the function result. A function to transform items from the input sequence into comparable keys. The input sequence. The smallest element of the sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. let inputs = [ "aaa"; "b"; "cccc" ] inputs |> Seq.minBy (fun s -> s.Length) Evaluates to "b" let inputs = [] inputs |> Seq.minBy (fun (s: string) -> s.Length) Throws System.ArgumentException. Returns the lowest of all elements of the sequence, compared via Operators.min. The input sequence. The smallest element of the sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. let inputs = [10; 12; 11] inputs |> Seq.min Evaluates to 10 let inputs = [] inputs |> Seq.min Throws System.ArgumentException. Returns the greatest of all elements of the sequence, compared via Operators.max on the function result. A function to transform items from the input sequence into comparable keys. The input sequence. The largest element of the sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. let inputs = ["aaa"; "b"; "cccc"] inputs |> Seq.maxBy (fun s -> s.Length) Evaluates to "cccc" let inputs = [ ] inputs |> Seq.maxBy (fun s -> s.Length) Throws System.ArgumentException. Returns the greatest of all elements of the sequence, compared via Operators.max The input sequence. Thrown when the input sequence is null. Thrown when the input sequence is empty. The largest element of the sequence. let inputs = [ 10; 12; 11 ] inputs |> Seq.max Evaluates to 12 let inputs = [ ] inputs |> Seq.max Throws System.ArgumentException. Builds a new collection whose elements are the results of applying the given function to the corresponding pairs of elements from the two sequences. If one input sequence is shorter than the other then the remaining elements of the longer sequence are ignored. The integer index passed to the function indicates the index (from 0) of element being transformed. A function to transform pairs of items from the input sequences that also supplies the current index. The first input sequence. The second input sequence. The result sequence. Thrown when either of the input sequences is null. let inputs1 = ["a"; "bad"; "good"] let inputs2 = [0; 2; 1] (inputs1, inputs2) ||> Seq.mapi2 (fun i x y -> i, x[y]) Evaluates to a sequence yielding the same results as seq { (0, 'a'); (1, 'd'); (2, 'o') } Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The integer index passed to the function indicates the index (from 0) of element being transformed. A function to transform items from the input sequence that also supplies the current index. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = [ 10; 10; 10 ] inputs |> Seq.mapi (fun i x -> i + x) Evaluates to a sequence yielding the same results as seq { 10; 11; 12 } Builds a new collection whose elements are the results of applying the given function to the corresponding triples of elements from the three sequences. If one input sequence if shorter than the others then the remaining elements of the longer sequences are ignored. The function to transform triples of elements from the input sequences. The first input sequence. The second input sequence. The third input sequence. The result sequence. Thrown when any of the input sequences is null. let inputs1 = [ "a"; "t"; "ti" ] let inputs2 = [ "l"; "h"; "m" ] let inputs3 = [ "l"; "e"; "e" ] (inputs1, inputs2, inputs3) |||> Seq.map3 (fun x y z -> x + y + z) Evaluates to a sequence yielding the same results as seq { "all"; "the"; "time" } Combines map and foldBack. Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The function is also used to accumulate a final value. This function digests the whole initial sequence as soon as it is called. As a result this function should not be used with large or infinite sequences. The function to transform elements from the input collection and accumulate the final value. The input collection. The initial state. Thrown when the input collection is null. The collection of transformed elements, and the final accumulated value. Accumulate the charges from back to front, and double them as well type Charge = | In of int | Out of int let inputs = seq { In 1; Out 2; In 3 } let newCharges, balance = (inputs, 0) ||> Seq.mapFoldBack (fun charge acc -> match charge with | In i -> In (i*2), acc + i | Out o -> Out (o*2), acc - o) Evaluates newCharges to seq { In 2; Out 4; In 6 } and balance to 2. Combines map and fold. Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The function is also used to accumulate a final value. This function digests the whole initial sequence as soon as it is called. As a result this function should not be used with large or infinite sequences. The function to transform elements from the input collection and accumulate the final value. The initial state. The input collection. Thrown when the input collection is null. The collection of transformed elements, and the final accumulated value. Accumulate the charges, and double them as well type Charge = | In of int | Out of int let inputs = seq { In 1; Out 2; In 3 } let newCharges, balance = (0, inputs) ||> Seq.mapFold (fun acc charge -> match charge with | In i -> In (i*2), acc + i | Out o -> Out (o*2), acc - o) Evaluates newCharges to seq { In 2; Out 4; In 6 } and balance to 2. Builds a new collection whose elements are the results of applying the given function to the corresponding pairs of elements from the two sequences. If one input sequence is shorter than the other then the remaining elements of the longer sequence are ignored. A function to transform pairs of items from the input sequences. The first input sequence. The second input sequence. The result sequence. Thrown when either of the input sequences is null. let inputs1 = ["a"; "bad"; "good"] let inputs2 = [0; 2; 1] (inputs1, inputs2) ||> Seq.map2 (fun x y -> x.[y]) Evaluates to a sequence yielding the same results as seq { 'a'; 'd'; 'o' } Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The given function will be applied as elements are demanded using the MoveNext method on enumerators retrieved from the object. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. A function to transform items from the input sequence. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = ["a"; "bbb"; "cc"] inputs |> Seq.map (fun x -> x.Length) Evaluates to a sequence yielding the same results as seq { 1; 3; 2 } Returns the length of the sequence The input sequence. The length of the sequence. Thrown when the input sequence is null. let inputs = ["a"; "b"; "c"] inputs |> Seq.length Evaluates to 3 Applies the given function to two collections simultaneously. If one sequence is shorter than the other then the remaining elements of the longer sequence are ignored. The integer passed to the function indicates the index of element. A function to apply to each pair of elements from the input sequences along with their index. The first input sequence. The second input sequence. Thrown when either of the input sequences is null. let inputs1 = ["a"; "b"; "c"] let inputs2 = ["banana"; "pear"; "apple"] (inputs1, inputs2) ||> Seq.iteri2 (fun i s1 s2 -> printfn "Index {i}: {s1} - {s2}") Evaluates to unit and prints Index 0: a - banana Index 1: b - pear Index 2: c - apple in the console. Applies the given function to two collections simultaneously. If one sequence is shorter than the other then the remaining elements of the longer sequence are ignored. A function to apply to each pair of elements from the input sequences. The first input sequence. The second input sequence. Thrown when either of the input sequences is null. let inputs1 = ["a"; "b"; "c"] let inputs2 = [1; 2; 3] (inputs1, inputs2) ||> Seq.iter2 (printfn "%s: %i") Evaluates to unit and prints a: 1 b: 2 c: 3 in the console. Applies the given function to each element of the collection. The integer passed to the function indicates the index of element. A function to apply to each element of the sequence that can also access the current index. The input sequence. Thrown when the input sequence is null. let inputs = ["a"; "b"; "c"] inputs |> Seq.iteri (fun i v -> printfn "{i}: {v}") Evaluates to unit and prints 0: a 1: b 2: c in the console. Applies the given function to each element of the collection. A function to apply to each element of the sequence. The input sequence. Thrown when the input sequence is null. ["a"; "b"; "c"] |> Seq.iter (printfn "%s") Evaluates to unit and prints a b c in the console. Computes the element at the specified index in the collection. The index of the element to retrieve. The input sequence. The element at the specified index of the sequence. Thrown when the input sequence is null. Thrown when the index is negative or the input sequence does not contain enough elements. let inputs = ["a"; "b"; "c"] inputs |> Seq.item 1 Evaluates to "b" let inputs = ["a"; "b"; "c"] inputs |> Seq.item 4 Throws ArgumentException Generates a new sequence which, when iterated, will return successive elements by calling the given function. The results of calling the function will not be saved, that is the function will be reapplied as necessary to regenerate the elements. The function is passed the index of the item being generated. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. Iteration can continue up to Int32.MaxValue. A function that generates an item in the sequence from a given index. The result sequence. (+) 5 |> Seq.initInfinite Evaluates to a sequence yielding the same results as seq { 5; 6; 7; 8; ... } Generates a new sequence which, when iterated, will return successive elements by calling the given function, up to the given count. Each element is saved after its initialization. The function is passed the index of the item being generated. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. The maximum number of items to generate for the sequence. A function that generates an item in the sequence from a given index. The result sequence. Thrown when count is negative. Seq.init 4 (fun v -> v + 5) Evaluates to a sequence yielding the same results as seq { 5; 6; 7; 8 } Seq.init -5 (fun v -> v + 5) Throws ArgumentException Builds a new collection whose elements are the corresponding elements of the input collection paired with the integer index (from 0) of each element. The input sequence. The result sequence. Thrown when the input sequence is null. ["a"; "b"; "c"] |> Seq.indexed Evaluates to a sequence yielding the same results as seq { (0, "a"); (1, "b"); (2, "c") } Returns true if the sequence contains no elements, false otherwise. The input sequence. True if the sequence is empty; false otherwise. Thrown when the input sequence is null. [] |> Seq.isEmpty Evaluates to true ["pear"; "banana"] |> Seq.isEmpty Evaluates to false Returns the only element of the sequence or None if sequence is empty or contains more than one element. The input sequence. The only element of the sequence or None. Thrown when the input sequence is null. let inputs = ["banana"] inputs |> Seq.tryExactlyOne Evaluates to Some banana let inputs = ["pear"; "banana"] inputs |> Seq.tryExactlyOne Evaluates to None [] |> Seq.tryExactlyOne Evaluates to None Returns the only element of the sequence. The input sequence. The only element of the sequence. Thrown when the input sequence is null. Thrown when the input does not have precisely one element. let inputs = ["banana"] inputs |> Seq.exactlyOne Evaluates to banana let inputs = ["pear"; "banana"] inputs |> Seq.exactlyOne Throws ArgumentException [] |> Seq.exactlyOne Throws ArgumentException Returns the last element of the sequence. Return None if no such element exists. The input sequence. The last element of the sequence or None. Thrown when the input sequence is null. ["pear"; "banana"] |> Seq.tryLast Evaluates to Some "banana" [] |> Seq.tryLast Evaluates to None Returns the last element of the sequence. The input sequence. The last element of the sequence. Thrown when the input sequence is null. Thrown when the input does not have any elements. ["pear"; "banana"] |> Seq.last Evaluates to banana [] |> Seq.last Throws ArgumentException Returns the first element of the sequence, or None if the sequence is empty. The input sequence. The first element of the sequence or None. Thrown when the input sequence is null. ["banana"; "pear"] |> Seq.tryHead Evaluates to Some "banana" [] |> Seq.tryHead Evaluates to None Returns the first element of the sequence. The input sequence. The first element of the sequence. Thrown when the input sequence is null. Thrown when the input does not have any elements. let inputs = ["banana"; "pear"] inputs |> Seq.head Evaluates to banana [] |> Seq.head Throws ArgumentException Applies a key-generating function to each element of a sequence and yields a sequence of unique keys. Each unique key contains a sequence of all elements that match to this key. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence. A function that transforms an element of the sequence into a comparable key. The input sequence. The result sequence. let inputs = [1; 2; 3; 4; 5] inputs |> Seq.groupBy (fun n -> n % 2) Evaluates to a sequence yielding the same results as seq { (1, seq { 1; 3; 5 }); (0, seq { 2; 4 }) } Tests the all pairs of elements drawn from the two sequences satisfy the given predicate. If one sequence is shorter than the other then the remaining elements of the longer sequence are ignored. A function to test pairs of elements from the input sequences. The first input sequence. The second input sequence. True if all pairs satisfy the predicate; false otherwise. Thrown when either of the input sequences is null. let inputs1 = [1; 2; 3; 4; 5; 6] let inputs2 = [1; 2; 3; 4; 5] (inputs1, inputs2) ||> Seq.forall2 (=) Evaluates to true. let items1 = [2017; 1; 1] let items2 = [2019; 19; 8] (items1, items2) ||> Seq.forall2 (=) Evaluates to false. Tests if all elements of the sequence satisfy the given predicate. The predicate is applied to the elements of the input sequence. If any application returns false then the overall result is false and no further elements are tested. Otherwise, true is returned. A function to test an element of the input sequence. The input sequence. True if every element of the sequence satisfies the predicate; false otherwise. Thrown when the input sequence is null. let isEven a = a % 2 = 0 [2; 42] |> Seq.forall isEven // evaluates to true [1; 2] |> Seq.forall isEven // evaluates to false Applies a function to corresponding elements of two collections, starting from the end of the shorter collection, threading an accumulator argument through the computation. The two sequences need not have equal lengths. If the input function is f and the elements are i0...iN and j0...jM, N < M then computes f i0 j0 (... (f iN jN s)...). The function to update the state given the input elements. The first input sequence. The second input sequence. The initial state. The final state value. Thrown when the either of the input sequences is null. This function consumes the whole of both inputs sequences before returning the result. As a result this function should not be used with large or infinite sequences. type Count = { Positive: int Negative: int Text: string } let inputs1 = [-1; -2; -3] let inputs2 = [3; 2; 1; 0] let initialState = {Positive = 0; Negative = 0; Text = ""} (inputs1, inputs2, initialState) |||> Seq.foldBack2 (fun a b acc -> let text = acc.Text + "(" + string a + "," + string b + ") " if a + b >= 0 then { acc with Positive = acc.Positive + 1 Text = text } else { acc with Negative = acc.Negative + 1 Text = text } ) Evaluates to { Positive = 2 Negative = 1 Text = " (-3,1) (-2,2) (-1,3)" } Applies a function to each element of the collection, starting from the end, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f i0 (... (f iN s)...) The function to update the state given the input elements. The input sequence. The initial state. The state object after the folding function is applied to each element of the sequence. Thrown when the input sequence is null. This function consumes the whole input sequence before returning the result. type Count = { Positive: int Negative: int Text: string } let sequence = [1; 0; -1; -2; 3] let initialState = {Positive = 0; Negative = 0; Text = ""} (sequence, initialState) ||> Seq.foldBack (fun a acc -> let text = acc.Text + " " + string a if a >= 0 then { acc with Positive = acc.Positive + 1 Text = text } else { acc with Negative = acc.Negative + 1 Text = text }) Evaluates to { Positive = 2 Negative = 3 Text = " 3 -2 -1 0 1" } Applies a function to corresponding elements of two collections, threading an accumulator argument through the computation. The two sequences need not have equal lengths: when one sequence is exhausted any remaining elements in the other sequence are ignored. If the input function is f and the elements are i0...iN and j0...jN then computes f (... (f s i0 j0)...) iN jN. The function to update the state given the input elements. The initial state. The first input sequence. The second input sequence. The final state value. Thrown when the either of the input sequences is null. type CoinToss = Head | Tails let data1 = [Tails; Head; Tails] let data2 = [Tails; Head; Head] (0, data1, data2) |||> Seq.fold2 (fun acc a b -> match (a, b) with | Head, Head -> acc + 1 | Tails, Tails -> acc + 1 | _ -> acc - 1) Evaluates to 1 Applies a function to each element of the collection, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f (... (f s i0)...) iN A function that updates the state with each element from the sequence. The initial state. The input sequence. The state object after the folding function is applied to each element of the sequence. Thrown when the input sequence is null. type Charge = | In of int | Out of int let inputs = [In 1; Out 2; In 3] (0, inputs) ||> Seq.fold (fun acc charge -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to 2 Returns the index of the last element for which the given function returns True. This function digests the whole initial sequence as soon as it is called. As a result this function should not be used with large or infinite sequences. A function to test whether the index of a particular element should be returned. The input sequence. The index of the last element for which the predicate returns True. Thrown if no element returns true when evaluated by the predicate Thrown when the input sequence is null let input = [1; 2; 3; 4; 5] input |> Seq.findIndex (fun elm -> elm % 2 = 0) Evaluates to 3 let input = [1; 2; 3; 4; 5] input |> Seq.findIndex (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns the index of the first element for which the given function returns True. A function to test whether the index of a particular element should be returned. The input sequence. The index of the first element for which the predicate returns True. Thrown if no element returns true when evaluated by the predicate Thrown when the input sequence is null let inputs = [1; 2; 3; 4; 5] inputs |> Seq.findIndex (fun elm -> elm % 2 = 0) Evaluates to 1 let inputs = [1; 2; 3; 4; 5] inputs |> Seq.findIndex (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns the last element for which the given function returns True. This function digests the whole initial sequence as soon as it is called. As a result this function should not be used with large or infinite sequences. A function to test whether an item in the sequence should be returned. The input sequence. The last element for which the predicate returns True. Thrown if no element returns true when evaluated by the predicate Thrown when the input sequence is null let inputs = [2; 3; 4] inputs |> Seq.findBack (fun elm -> elm % 2 = 0) Evaluates to 4 let inputs = [2; 3; 4] inputs |> Seq.findBack (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns the first element for which the given function returns True. A function to test whether an item in the sequence should be returned. The input sequence. The first element for which the predicate returns True. Thrown if no element returns true when evaluated by the predicate Thrown when the input sequence is null let inputs = [1; 2; 3] inputs |> Seq.find (fun elm -> elm % 2 = 0) Evaluates to 2 let inputs = [1; 2; 3] inputs |> Seq.find (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns a new collection containing only the elements of the collection for which the given predicate returns "true". The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. Remember sequence is lazy, effects are delayed until it is enumerated. A synonym for Seq.filter. A function to test whether each item in the input sequence should be included in the output. The input sequence. The result sequence. Thrown when the input sequence is null. [1; 2; 3; 4] |> Seq.where (fun elm -> elm % 2 = 0) Evaluates to a sequence yielding the same results as seq { 2; 4 } Returns a new collection containing only the elements of the collection for which the given predicate returns "true". This is a synonym for Seq.where. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. Remember sequence is lazy, effects are delayed until it is enumerated. A function to test whether each item in the input sequence should be included in the output. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = [1; 2; 3; 4] inputs |> Seq.filter (fun elm -> elm % 2 = 0) Evaluates to a sequence yielding the same results as seq { 2; 4 } Tests if any pair of corresponding elements of the input sequences satisfies the given predicate. The predicate is applied to matching elements in the two sequences up to the lesser of the two lengths of the collections. If any application returns true then the overall result is true and no further elements are tested. Otherwise, false is returned. If one sequence is shorter than the other then the remaining elements of the longer sequence are ignored. A function to test each pair of items from the input sequences. The first input sequence. The second input sequence. True if any result from the predicate is true; false otherwise. Thrown when either of the two input sequences is null. let inputs1 = [1; 2] let inputs2 = [1; 2; 0] (inputs1, inputs2) ||> Seq.exists2 (fun a b -> a > b) Evaluates to false let inputs1 = [1; 4] let inputs2 = [1; 3; 5] (inputs1, inputs2) ||> Seq.exists2 (fun a b -> a > b) Evaluates to true Tests if any element of the sequence satisfies the given predicate. The predicate is applied to the elements of the input sequence. If any application returns true then the overall result is true and no further elements are tested. Otherwise, false is returned. A function to test each item of the input sequence. The input sequence. True if any result from the predicate is true; false otherwise. Thrown when the input sequence is null. let input = [1; 2; 3; 4; 5] input |> Seq.exists (fun elm -> elm % 4 = 0) Evaluates to true let input = [1; 2; 3; 4; 5] input |> Seq.exists (fun elm -> elm % 6 = 0) Evaluates to false Returns a new sequence with the distinct elements of the second sequence which do not appear in the first sequence, using generic hash and equality comparisons to compare values. Note that this function returns a sequence that digests the whole of the first input sequence as soon as the result sequence is iterated. As a result this function should not be used with large or infinite sequences in the first parameter. The function makes no assumption on the ordering of the first input sequence. A sequence whose elements that also occur in the second sequence will cause those elements to be removed from the returned sequence. A sequence whose elements that are not also in first will be returned. A sequence that contains the set difference of the elements of two sequences. Thrown when either of the two input sequences is null. let original = [1; 2; 3; 4; 5] let itemsToExclude = [1; 3; 5] original |> Seq.except itemsToExclude Evaluates to a sequence yielding the same results as seq { 2; 4 } Creates an empty sequence. An empty sequence. Seq.empty // Evaluates to seq { } Splits the input sequence into at most count chunks. This function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The maximum number of chunks. The input sequence. The sequence split into chunks. Thrown when the input sequence is null. Thrown when count is not positive. This function consumes the whole input sequence before yielding the first element of the result sequence. let inputs = [1; 2; 3; 4; 5] inputs |> Seq.splitInto 3 Evaluates to a sequence yielding the same results as seq { [|1; 2|]; [|3; 4|]; [|5|] } let inputs = [1; 2; 3; 4; 5] inputs |> Seq.splitInto -1 Throws ArgumentException Returns a sequence that contains no duplicate entries according to the generic hash and equality comparisons on the keys returned by the given key-generating function. If an element occurs multiple times in the sequence then the later occurrences are discarded. A function transforming the sequence items into comparable keys. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = [{Bar = 1 };{Bar = 1}; {Bar = 2}; {Bar = 3}] inputs |> Seq.distinctBy (fun foo -> foo.Bar) Evaluates to a sequence yielding the same results as seq { { Bar = 1 }; { Bar = 2 }; { Bar = 3 } } Returns a sequence that contains no duplicate entries according to generic hash and equality comparisons on the entries. If an element occurs multiple times in the sequence then the later occurrences are discarded. The input sequence. The result sequence. Thrown when the input sequence is null. [1; 1; 2; 3] |> Seq.distinct Evaluates to a sequence yielding the same results as seq { 1; 2; 3 } Returns a sequence that is built from the given delayed specification of a sequence. The input function is evaluated each time an IEnumerator for the sequence is requested. The generating function for the sequence. The result sequence. Seq.delay (fun () -> Seq.ofList [1; 2; 3]) Evaluates to a sequence yielding the same results as seq { 1; 2; 3 }, executing the generator function every time is consumed. Applies a key-generating function to each element of a sequence and returns a sequence yielding unique keys and their number of occurrences in the original sequence. Note that this function returns a sequence that digests the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence. A function transforming each item of the input sequence into a key to be compared against the others. The input sequence. The result sequence. Thrown when the input sequence is null. type Foo = { Bar: string } let inputs = [{Bar = "a"}; {Bar = "b"}; {Bar = "a"}] inputs |> Seq.countBy (fun foo -> foo.Bar) Evaluates to a sequence yielding the same results as seq { ("a", 2); ("b", 1) } Tests if the sequence contains the specified element. The value to locate in the input sequence. The input sequence. True if the input sequence contains the specified element; false otherwise. Thrown when the input sequence is null. [1; 2] |> Seq.contains 2 // evaluates to true [1; 2] |> Seq.contains 5 // evaluates to false Combines the given enumeration-of-enumerations as a single concatenated enumeration. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. The input enumeration-of-enumerations. The result sequence. Thrown when the input sequence is null. let inputs = [[1; 2]; [3]; [4; 5]] inputs |> Seq.concat Evaluates to a sequence yielding the same results as seq { 1; 2; 3; 4; 5 } Compares two sequences using the given comparison function, element by element. A function that takes an element from each sequence and returns an int. If it evaluates to a non-zero value iteration is stopped and that value is returned. The first input sequence. The second input sequence. Returns the first non-zero result from the comparison function. If the end of a sequence is reached it returns a -1 if the first sequence is shorter and a 1 if the second sequence is shorter. Thrown when either of the input sequences is null. let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 10] let input2 = [1; 10] (input1, input2) ||> Seq.compareWith closerToNextDozen Evaluates to 0 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 5] let input2 = [1; 8] (input1, input2) ||> Seq.compareWith closerToNextDozen Evaluates to -1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 11] let input2 = [1; 13] (input1, input2) ||> Seq.compareWith closerToNextDozen Evaluates to 1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 2] let input2 = [1] (input1, input2) ||> Seq.compareWith closerToNextDozen Evaluates to 1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1] let input2 = [1; 2] (input1, input2) ||> Seq.compareWith closerToNextDozen Evaluates to -1 Applies the given function to each element of the sequence and concatenates all the results. Remember sequence is lazy, effects are delayed until it is enumerated. A function to transform elements of the input sequence into the sequences that will then be concatenated. The input sequence. The result sequence. Thrown when the input sequence is null. type Foo = { Bar: int seq } let input = seq { {Bar = [1; 2]}; {Bar = [3; 4]} } input |> Seq.collect (fun foo -> foo.Bar) Evaluates to a sequence yielding the same results as seq { 1; 2; 3; 4 } let input = [[1; 2]; [3; 4]] input |> Seq.collect id Evaluates to a sequence yielding the same results as seq { 1; 2; 3; 4 } Divides the input sequence into chunks of size at most chunkSize. The maximum size of each chunk. The input sequence. The sequence divided into chunks. Thrown when the input sequence is null. Thrown when chunkSize is not positive. [1; 2; 3] |> Seq.chunkBySize 2 Evaluates to a sequence yielding the same results as seq { [|1; 2|]; [|3|] } [1; 2; 3] |> Seq.chunkBySize -2 Throws ArgumentException Applies the given function to each element of the sequence. Returns a sequence comprised of the results "x" for each element where the function returns Some(x). The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. A function to transform items of type T into options of type U. The input sequence of type T. The result sequence. Thrown when the input sequence is null. [Some 1; None; Some 2] |> Seq.choose id Evaluates to a sequence yielding the same results as seq { 1; 2 } [1; 2; 3] |> Seq.choose (fun n -> if n % 2 = 0 then Some n else None) Evaluates to a sequence yielding the same results as seq { 2 } Wraps a loosely-typed System.Collections sequence as a typed sequence. The use of this function usually requires a type annotation. An incorrect type annotation may result in runtime type errors. Individual IEnumerator values generated from the returned sequence should not be accessed concurrently. The input sequence. The result sequence. Thrown when the input sequence is null. [box 1; box 2; box 3] |> Seq.cast<int> Evaluates to a sequence yielding the same results as seq { 1; 2; 3 }, explicitly typed as seq<int>. Returns a sequence that corresponds to a cached version of the input sequence. The result sequence will have the same elements as the input sequence. The result can be enumerated multiple times. The input sequence will be enumerated at most once and only as far as is necessary. Caching a sequence is typically useful when repeatedly evaluating items in the original sequence is computationally expensive or if iterating the sequence causes side-effects that the user does not want to be repeated multiple times. Enumeration of the result sequence is thread safe in the sense that multiple independent IEnumerator values may be used simultaneously from different threads (accesses to the internal lookaside table are thread safe). Each individual IEnumerator is not typically thread safe and should not be accessed concurrently. Once enumeration of the input sequence has started, it's enumerator will be kept live by this object until the enumeration has completed. At that point, the enumerator will be disposed. The enumerator may be disposed and underlying cache storage released by converting the returned sequence object to type IDisposable, and calling the Dispose method on this object. The sequence object may then be re-enumerated and a fresh enumerator will be used. The input sequence. The result sequence. Thrown when the input sequence is null. let fibSeq =(0, 1) |> Seq.unfold (fun (a,b) -> Some(a + b, (b, a + b))) let fibSeq3 = fibSeq |> Seq.take 3 |> Seq.cache fibSeq3 Evaluates to a sequence yielding the same results as seq { 1; 2; 3 }, and it will not do the calculation again when called. Returns the average of the results generated by applying the function to each element of the sequence. The elements are averaged using the + operator, DivideByInt method and Zero property associated with the generated type. A function applied to transform each element of the sequence. The input sequence. The average. Thrown when the input sequence is null. Thrown when the input sequence has zero elements. type Foo = { Bar: float } let input = seq { {Bar = 2.0}; {Bar = 4.0} } input |> Seq.averageBy (fun foo -> foo.Bar) Evaluates to 3.0 type Foo = { Bar: float } Seq.empty |> Seq.averageBy (fun (foo: Foo) -> foo.Bar) Throws ArgumentException Returns the average of the elements in the sequence. The elements are averaged using the + operator, DivideByInt method and Zero property associated with the element type. The input sequence. The average. Thrown when the input sequence is null. Thrown when the input sequence has zero elements. [1.0; 2.0; 3.0] |> Seq.average Evaluates to 2.0 [] |> Seq.average Throws ArgumentException Wraps the two given enumerations as a single concatenated enumeration. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. The first sequence. The second sequence. The result sequence. Thrown when either of the two provided sequences is null. Seq.append [1; 2] [3; 4] Evaluates to a sequence yielding the same results as seq { 1; 2; 3; 4 } Returns a new sequence that contains all pairings of elements from the first and second sequences. The first sequence. The second sequence. The result sequence. Thrown when either of the input sequences is null. ([1; 2], [3; 4]) ||> Seq.allPairs Evaluates to a sequence yielding the same results as seq { (1, 3); (1, 4); (2, 3); (2, 4) } Contains operations for working with values of type . Returns a random sample of elements from the given list using the specified randomizer function, each element can be selected only once. The randomizer function, must return a float number from [0.0..1.0) range. The number of elements to return. The input list. A list of randomly selected elements from the input list. Thrown when the input list is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input list. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomSampleBy Random.Shared.NextDouble 3 Can evaluate to [ 3; 1; 2 ]. Returns a random sample of elements from the given list with the specified Random instance, each element can be selected only once. The Random instance. The number of elements to return. The input list. A list of randomly selected elements from the input list. Thrown when the random argument is null. Thrown when the input list is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input list. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomSampleWith Random.Shared 3 Can evaluate to [ 3; 1; 2 ]. Returns a random sample of elements from the given list, each element can be selected only once. The number of elements to return. The input list. A list of randomly selected elements from the input list. Thrown when the input list is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input list. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomSample 3 Can evaluate to [ 3; 1; 2 ]. Returns a list of random elements from the given list using the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The number of elements to return. The input list. A list of randomly selected elements from the input list. Thrown when the input list is empty. Thrown when count is less than 0. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomChoicesBy Random.Shared.NextDouble 3 Can evaluate to [ 3; 1; 3 ]. Returns a list of random elements from the given list with the specified Random instance, each element can be selected multiple times. The Random instance. The number of elements to return. The input list. A list of randomly selected elements from the input list. Thrown when the random argument is null. Thrown when the input list is empty. Thrown when count is less than 0. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> Array.randomChoicesWith Random.Shared 3 Can evaluate to [ 3; 1; 3 ]. Returns a list of random elements from the given list. The number of elements to return. The input list. A list of randomly selected elements from the input list. Thrown when the input list is empty. Thrown when count is less than 0. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomChoices 3 Can evaluate to [ 3; 1; 3 ]. Returns a random element from the given list using the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The input list. A randomly selected element from the input list. Thrown when the input list is empty. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomChoiceBy Random.Shared.NextDouble Can evaluate to 3. Returns a random element from the given list with the specified Random instance, each element can be selected multiple times. The Random instance. The input list. A randomly selected element from the input list. Thrown when the random argument is null. Thrown when the input list is empty. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomChoiceWith Random.Shared Can evaluate to 3. Returns a random element from the given list. The input list. A randomly selected element from the input list. Thrown when the input list is empty. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomChoice Can evaluate to 3. Return a new list shuffled in a random order using the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The input list. The result list. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomShuffleBy Random.Shared.NextDouble Can evaluate to [ 0; 2; 4; 3; 1 ]. Return a new list shuffled in a random order with the specified Random instance. The Random instance. The input list. The result list. Thrown when the random argument is null. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomShuffleWith Random.Shared Can evaluate to [ 0; 2; 4; 3; 1 ]. Return a new list shuffled in a random order. The input list. The result list. let inputs = [ 0; 1; 2; 3; 4 ] inputs |> List.randomShuffle Can evaluate to [ 0; 2; 4; 3; 1 ]. Return a new list with new items inserted before the given index. The index where the items should be inserted. The values to insert. The input list. The result list. Thrown when index is below 0 or greater than source.Length. let inputs = [ 0; 1; 2 ] inputs |> List.insertManyAt 1 [ 8; 9 ] Evaluates to [ 0; 8; 9; 1; 2 ]. Return a new list with a new item inserted before the given index. The index where the item should be inserted. The value to insert. The input list. The result list. Thrown when index is below 0 or greater than source.Length. let inputs = [ 0; 1; 2 ] inputs |> List.insertAt 1 9 Evaluates to [ 0; 9; 1; 2 ]. Return a new list with the item at a given index set to the new value. The index of the item to be replaced. The new value. The input list. The result list. Thrown when index is outside 0..source.Length - 1 let inputs = [ 0; 1; 2 ] inputs |> List.updateAt 1 9 Evaluates to [ 0; 9; 2 ]. Return a new list with the number of items starting at a given index removed. The index of the item to be removed. The number of items to remove. The input list. The result list. Thrown when index is outside 0..source.Length - count let inputs = [ 0; 1; 2; 3 ] inputs |> List.removeManyAt 1 2 Evaluates to [ 0; 3 ]. Return a new list with the item at a given index removed. The index of the item to be removed. The input list. The result list. Thrown when index is outside 0..source.Length - 1 let inputs = [ 0; 1; 2 ] inputs |> List.removeAt 1 let inputs = [ 0; 2 ] Combines the three lists into a list of triples. The lists must have equal lengths. The first input list. The second input list. The third input list. A single list containing triples of matching elements from the input lists. let numbers = [1; 2] let names = ["one"; "two"] let roman = ["I"; "II"] List.zip3 numbers names roman Evaluates to [(1, "one", "I"); (2, "two", "II")]. Combines the two lists into a list of pairs. The two lists must have equal lengths. The first input list. The second input list. A single list containing pairs of matching elements from the input lists. let numbers = [1; 2] let names = ["one"; "two"] List.zip numbers names Evaluates to [(1, "one"); (2, "two")]. Returns a list of sliding windows containing elements drawn from the input list. Each window is returned as a fresh list. The number of elements in each window. The input list. The result list. Thrown when windowSize is not positive. let inputs = [1; 2; 3; 4; 5] inputs |> List.windowed 3 Evaluates to [[1; 2; 3]; [2; 3; 4]; [3; 4; 5]] Returns a new list containing only the elements of the list for which the given predicate returns "true" The function to test the input elements. The input list. A list containing only the elements that satisfy the predicate. This is identical to List.filter. Select only the even numbers: let inputs = [1; 2; 3; 4] inputs |> List.where (fun elm -> elm % 2 = 0) Evaluates to [2; 4] Splits a list of triples into three lists. The input list. Three lists of split elements. let inputs = [(1, "one", "I"); (2, "two", "II")] let numbers, names, roman = inputs |> List.unzip3 Evaluates numbers to [1; 2], names to ["one"; "two"] and roman to ["I"; "II"]. Splits a list of pairs into two lists. The input list. Two lists of split elements. let inputs = [(1, "one"); (2, "two")] let numbers, names = inputs |> List.unzip Evaluates numbers to [1; 2] and names to ["one"; "two"]. Returns a list that contains the elements generated by the given computation. The generator is repeatedly called to build the list until it returns None. The given initial state argument is passed to the element generator. A function that takes in the current state and returns an option tuple of the next element of the list and the next state value. The initial state value. The result list. 1 |> List.unfold (fun state -> if state > 100 then None else Some (state, state * 2)) Evaluates to [1; 2; 4; 8; 16; 32; 64] Returns the index of the last element in the list that satisfies the given predicate. Return None if no such element exists. The function to test the input elements. The input list. The index of the last element for which the predicate returns true, or None if every element evaluates to false. Try to find the index of the first even number from the back: let inputs = [1; 2; 3; 4; 5] inputs |> List.tryFindIndexBack (fun elm -> elm % 2 = 0) Evaluates to Some 3 Try to find the index of the first even number from the back: let inputs = [1; 3; 5; 7] inputs |> List.tryFindIndexBack (fun elm -> elm % 2 = 0) Evaluates to None Tries to find the nth element in the list. Returns None if index is negative or the list does not contain enough elements. The index to retrieve. The input list. The value at the given index or None. let inputs = ["a"; "b"; "c"] inputs |> List.tryItem 1 Evaluates to Some "b". let inputs = ["a"; "b"; "c"] inputs |> List.tryItem 4 Evaluates to None. Returns the index of the first element in the list that satisfies the given predicate. Return None if no such element exists. The function to test the input elements. The input list. The index of the first element for which the predicate returns true, or None if every element evaluates to false. Try to find the index of the first even number: let inputs = [1; 2; 3; 4; 5] inputs |> List.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to Some 1 Try to find the index of the first even number: let inputs = [1; 3; 5; 7] inputs |> List.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to None Returns the last element for which the given function returns True. Return None if no such element exists. The function to test the input elements. The input list. The last element for which the predicate returns true, or None if every element evaluates to false. Try to find the first even number from the back: let inputs = [1; 2; 3; 4; 5] inputs |> List.tryFindBack (fun elm -> elm % 2 = 0) Evaluates to Some 4 Try to find the first even number from the back: let inputs = [1; 5; 3] inputs |> List.tryFindBack (fun elm -> elm % 2 = 0) Evaluates to None Returns the first element for which the given function returns True. Return None if no such element exists. The function to test the input elements. The input list. The first element for which the predicate returns true, or None if every element evaluates to false. Try to find the first even number: let inputs = [1; 2; 3] inputs |> List.tryFind (fun elm -> elm % 2 = 0) Evaluates to Some 2 Try to find the first even number: let inputs = [1; 5; 3] inputs |> List.tryFind (fun elm -> elm % 2 = 0) Evaluates to None Applies the given function to successive elements, returning Some(x) the first result where function returns Some(x) for some x. If no such element exists then return None. The function to generate options from the elements. The input list. The first resulting value or None. let input = [1; 2; 3] input |> List.tryPick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to Some "2". let input = [1; 2; 3] input |> List.tryPick (fun n -> if n > 3 then Some (string n) else None) Evaluates to None. Returns at most N elements in a new list. The maximum number of items to return. The input list. The result list. let inputs = ["a"; "b"; "c"; "d"] inputs |> List.truncate 2 Evaluates to ["a"; "b"] let inputs = ["a"; "b"; "c"; "d"] inputs |> List.truncate 6 Evaluates to ["a"; "b"; "c"; "d"] let inputs = ["a"; "b"; "c"; "d"] inputs |> List.truncate 0 Evaluates to the empty list. Returns the transpose of the given sequence of lists. The input sequence of list. The transposed list. Thrown when the input sequence is null. Thrown when the input lists differ in length. let inputs = [ [ 10; 20; 30 ] [ 11; 21; 31 ] ] inputs |> List.transpose Evaluates to [ [10; 11]; [20; 21]; [30; 31] ]. Returns the first element of the list, or None if the list is empty. The input list. The first element of the list or None. let inputs = [ "banana"; "pear" ] inputs |> List.tryHead Evaluates to Some "banana" let inputs : int list = [] inputs |> List.tryHead Evaluates to None Views the given list as a sequence. The input list. The sequence of elements in the list. let inputs = [ 1; 2; 5 ] inputs |> List.toSeq Evaluates to seq { 1; 2; 5 }. Builds an array from the given list. The input list. The array containing the elements of the list. let inputs = [ 1; 2; 5 ] inputs |> List.toArray Evaluates to [| 1; 2; 5 |]. Returns a list that contains all elements of the original list while the given predicate returns True, and then returns no further elements. A function that evaluates to false when no more items should be returned. The input list. The result list. let inputs = ["a"; "bb"; "ccc"; "d"] inputs |> List.takeWhile (fun x -> x.Length < 3) Evaluates to ["a"; "bb"] Returns the first N elements of the list. Throws InvalidOperationException if the count exceeds the number of elements in the list. List.truncate returns as many items as the list contains instead of throwing an exception. The number of items to take. The input list. The result list. Thrown when the input list is empty. Thrown when count exceeds the number of elements in the list. let inputs = ["a"; "b"; "c"; "d"] inputs |> List.take 2 Evaluates to ["a"; "b"] let inputs = ["a"; "b"; "c"; "d"] inputs |> List.take 6 Throws InvalidOperationException. let inputs = ["a"; "b"; "c"; "d"] inputs |> List.take 0 Evaluates to the empty list. Returns the list after removing the first element. The input list. Thrown when the list is empty. The list after removing the first element. let inputs = ["a"; "bb"; "ccc"] inputs |> List.tail Evaluates to ["bb"; "ccc"] Returns the sum of the results generated by applying the function to each element of the list. The function to transform the list elements into the type to be summed. The input list. The resulting sum. let input = [ "aa"; "bbb"; "cc" ] input |> List.sumBy (fun s -> s.Length) Evaluates to 7. Returns the sum of the elements in the list. The input list. The resulting sum. let input = [ 1; 5; 3; 2 ] input |> List.sum Evaluates to 11. Sorts the given list in descending order using . This is a stable sort, i.e. the original order of equal elements is preserved. The input list. The sorted list. let input = [8; 4; 3; 1; 6; 1] input |> List.sortDescending Evaluates to [8; 6; 4; 3; 1; 1]. Sorts the given list in descending order using keys given by the given projection. Keys are compared using . This is a stable sort, i.e. the original order of equal elements is preserved. The function to transform the list elements into the type to be compared. The input list. The sorted list. let input = ["a"; "bbb"; "cccc"; "dd"] input |> List.sortByDescending (fun s -> s.Length) Evaluates to ["cccc"; "bbb"; "dd"; "a"]. Splits a list into two lists, at the given index. The index at which the list is split. The input list. The two split lists. Thrown when split index exceeds the number of elements in the list. let input = [8; 4; 3; 1; 6; 1] let front, back = input |> List.splitAt 3 Evaluates front to [8; 4; 3] and back to [1; 6; 1]. Sorts the given list using . This is a stable sort, i.e. the original order of equal elements is preserved. The input list. The sorted list. let input = [8; 4; 3; 1; 6; 1] List.sort input Evaluates to [1; 1 3; 4; 6; 8]. Sorts the given list using keys given by the given projection. Keys are compared using . This is a stable sort, i.e. the original order of equal elements is preserved. The function to transform the list elements into the type to be compared. The input list. The sorted list. let input = [ "a"; "bbb"; "cccc"; "dd" ] input |> List.sortBy (fun s -> s.Length) Evaluates to ["a"; "dd"; "bbb"; "cccc"]. Sorts the given list using the given comparison function. This is a stable sort, i.e. the original order of equal elements is preserved. The function to compare the list elements. The input list. The sorted list. Sort a list of pairs using a comparison function that compares string lengths then index numbers: let compareEntries (n1: int, s1: string) (n2: int, s2: string) = let c = compare s1.Length s2.Length if c <> 0 then c else compare n1 n2 let input = [ (0,"aa"); (1,"bbb"); (2,"cc"); (3,"dd") ] input |> List.sortWith compareEntries Evaluates to [(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")]. Bypasses elements in a list while the given predicate returns True, and then returns the remaining elements of the list. A function that evaluates an element of the list to a boolean value. The input list. The result list. let inputs = ["a"; "bbb"; "cc"; "d"] inputs |> List.skipWhile (fun x -> x.Length < 3) Evaluates to ["bbb"; "cc"; "d"] Returns the list after removing the first N elements. The number of elements to skip. If the number is 0 or negative the input list is returned. The input list. The list after removing the first N elements. Thrown when count exceeds the number of elements in the list. let inputs = ["a"; "b"; "c"; "d"] inputs |> List.skip 2 Evaluates to ["c"; "d"] let inputs = ["a"; "b"; "c"; "d"] inputs |> List.skip 5 Throws ArgumentException. let inputs = ["a"; "b"; "c"; "d"] inputs |> List.skip -1 Evaluates to ["a"; "b"; "c"; "d"]. Returns a list that contains one item only. The input item. The result list of one item. List.singleton 7 Evaluates to [ 7 ]. Like foldBack, but returns both the intermediary and final results The function to update the state given the input elements. The input list. The initial state. The list of states. Apply a list charges from back to front, and collect the running balances as each is applied: type Charge = | In of int | Out of int let inputs = [ In 1; Out 2; In 3 ] (inputs, 0) ||> List.scanBack (fun charge acc -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to [2; 1; 3; 0] by processing each input from back to front. Note 0 is the initial state, 3 the next state, 1 the next state, and 2 the final state, and the states are produced from back to front. Note acc is a commonly used abbreviation for "accumulator". Applies a function to each element of the collection, threading an accumulator argument through the computation. Take the second argument, and apply the function to it and the first element of the list. Then feed this result into the function along with the second element and so on. Returns the list of intermediate results and the final result. The function to update the state given the input elements. The initial state. The input list. The list of states. Apply a list charges and collect the running balances as each is applied: type Charge = | In of int | Out of int let inputs = [In 1; Out 2; In 3] (0, inputs) ||> List.scan (fun acc charge -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to [0; 1; -1; 2]. Note 0 is the initial state, 1 the next state, -1 the next state, and 2 the final state. Note acc is a commonly used abbreviation for "accumulator". Returns a new list with the elements in reverse order. The input list. The reversed list. let inputs = [ 0; 1; 2 ] inputs |> List.rev Evaluates to [ 2; 1; 0 ]. Creates a list by replicating the given initial value. The number of elements to replicate. The value to replicate The generated list. List.replicate 3 "a" Evaluates to [ "a"; "a"; "a" ]. Applies a function to each element of the collection, starting from the end, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f i0 (...(f iN-1 iN)). A function that takes in the next-to-last element of the list and the current accumulated result to produce the next accumulated result. The input list. Thrown when the list is empty. The final result of the reductions. let inputs = [1; 3; 4; 2] inputs |> List.reduceBack (fun a b -> a + b * 10) Evaluates to 2431, by computing 1 + (3 + (4 + 2 * 10) * 10) * 10 Apply a function to each element of the collection, threading an accumulator argument through the computation. Apply the function to the first two elements of the list. Then feed this result into the function along with the third element and so on. Return the final result. If the input function is f and the elements are i0...iN then computes f (... (f i0 i1) i2 ...) iN. Raises if list is empty The function to reduce two list elements to a single element. The input list. Thrown when the list is empty. The final reduced value. let inputs = [1; 3; 4; 2] inputs |> List.reduce (fun a b -> a * 10 + b) Evaluates to 1342, by computing ((1 * 10 + 3) * 10 + 4) * 10 + 2 Returns a list with all elements permuted according to the specified permutation. The function to map input indices to output indices. The input list. The permuted list. Thrown when indexMap does not produce a valid permutation. let inputs = [1; 2; 3; 4] inputs |> List.permute (fun x -> (x + 1) % 4) Evaluates to [4; 1; 2; 3]. Applies the given function to successive elements, returning the first result where function returns Some(x) for some x. If no such element exists then raise The function to generate options from the elements. The input list. Thrown when the list is empty. The first resulting value. let input = [1; 2; 3] input |> List.pick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to "2". let input = [1; 2; 3] input |> List.pick (fun n -> if n > 3 then Some (string n) else None) Throws KeyNotFoundException. Splits the collection into two collections, containing the elements for which the given predicate returns True and False respectively. Element order is preserved in both of the created lists. The function to test the input elements. The input list. A list containing the elements for which the predicate evaluated to true and a list containing the elements for which the predicate evaluated to false. let inputs = [1; 2; 3; 4] let evens, odds = inputs |> List.partition (fun x -> x % 2 = 0) Evaluates evens to [2; 4] and odds to [1; 3]. Returns a list of each element in the input list and its predecessor, with the exception of the first element which is only returned as the predecessor of the second element. The input list. The result list. let inputs = [1; 2; 3; 4] inputs |> List.pairwise Evaluates to [(1, 2); (2, 3); (3, 4)]. Builds a new list from the given enumerable object. The input sequence. The list of elements from the sequence. let inputs = seq { 1; 2; 5 } inputs |> List.ofSeq Evaluates to [ 1; 2; 5 ]. Builds a list from the given array. The input array. The list of elements from the array. let inputs = [| 1; 2; 5 |] inputs |> List.ofArray Evaluates to [ 1; 2; 5 ]. Indexes into the list. The first element has index 0. The input list. The index to retrieve. The value at the given index. Thrown when the index is negative or the input list does not contain enough elements. Returns the lowest of all elements of the list, compared via Operators.min on the function result Raises if list is empty. The function to transform list elements into the type to be compared. The input list. Thrown when the list is empty. The minimum value. let inputs = ["aaa"; "b"; "cccc"] inputs |> List.minBy (fun s -> s.Length) Evaluates to "b" let inputs = [] inputs |> List.minBy (fun (s: string) -> s.Length) Throws System.ArgumentException. Returns the lowest of all elements of the list, compared via Operators.min. Raises if list is empty The input list. Thrown when the list is empty. The minimum value. let inputs = [10; 12; 11] inputs |> List.min Evaluates to 10 let inputs = [] inputs |> List.min Throws System.ArgumentException. Returns the greatest of all elements of the list, compared via Operators.max on the function result. Raises if list is empty. The function to transform the list elements into the type to be compared. The input list. Thrown when the list is empty. The maximum element. let inputs = ["aaa"; "b"; "cccc"] inputs |> List.maxBy (fun s -> s.Length) Evaluates to "cccc" let inputs = [] inputs |> List.maxBy (fun (s: string) -> s.Length) Throws System.ArgumentException. Return the greatest of all elements of the list, compared via Operators.max. Raises if list is empty The input list. Thrown when the list is empty. The maximum element. let inputs = [ 10; 12; 11 ] inputs |> List.max Evaluates to 12 let inputs = [ ] inputs |> List.max Throws System.ArgumentException. Like mapi, but mapping corresponding elements from two lists of equal length. The function to transform pairs of elements from the two lists and their index. The first input list. The second input list. The list of transformed elements. let inputs1 = ["a"; "bad"; "good"] let inputs2 = [0; 2; 1] (inputs1, inputs2) ||> List.mapi2 (fun i x y -> i, x[y]) Evaluates to [(0, 'a'); (1, 'd'); (2, 'o')] Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The integer index passed to the function indicates the index (from 0) of the element being transformed. The function to transform elements and their indices. The input list. The list of transformed elements. let inputs = [ 10; 10; 10 ] inputs |> List.mapi (fun i x -> i + x) Evaluates to [ 10; 11; 12 ] Combines map and foldBack. Builds a new list whose elements are the results of applying the given function to each of the elements of the input list. The function is also used to accumulate a final value. The function to transform elements from the input list and accumulate the final value. The input list. The initial state. The list of transformed elements, and the final accumulated value. Accumulate the charges from back to front, and double them as well type Charge = | In of int | Out of int let charges = [ In 1; Out 2; In 3 ] let newCharges, balance = (charges, 0) ||> List.mapFoldBack (fun charge acc -> match charge with | In i -> In (i*2), acc + i | Out o -> Out (o*2), acc - o) Evaluates newCharges to [In 2; Out 4; In 6] and balance to 2. Note acc is a commonly used abbreviation for "accumulator". Combines map and fold. Builds a new list whose elements are the results of applying the given function to each of the elements of the input list. The function is also used to accumulate a final value. The function to transform elements from the input list and accumulate the final value. The initial state. The input list. The list of transformed elements, and the final accumulated value. Accumulate the charges, and double them as well type Charge = | In of int | Out of int let inputs = [ In 1; Out 2; In 3 ] let newCharges, balance = (0, inputs) ||> List.mapFold (fun acc charge -> match charge with | In i -> In (i*2), acc + i | Out o -> Out (o*2), acc - o) Evaluates newCharges to [In 2; Out 4; In 6] and balance to 2. Note acc is a commonly used abbreviation for "accumulator". Builds a new collection whose elements are the results of applying the given function to the corresponding elements of the three collections simultaneously. The function to transform triples of elements from the input lists. The first input list. The second input list. The third input list. The list of transformed elements. let inputs1 = [ "a"; "t"; "ti" ] let inputs2 = [ "l"; "h"; "m" ] let inputs3 = [ "l"; "e"; "e" ] (inputs1, inputs2, inputs3) |||> List.map3 (fun x y z -> x + y + z) Evaluates to [ "all"; "the"; "time" ] Builds a new collection whose elements are the results of applying the given function to the corresponding elements of the two collections pairwise. The function to transform pairs of elements from the input lists. The first input list. The second input list. The list of transformed elements. let inputs1 = ["a"; "bad"; "good"] let inputs2 = [0; 2; 1] (inputs1, inputs2) ||> List.map2 (fun x y -> x.[y]) Evaluates to seq ['a'; 'd'; 'o'] Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The function to transform elements from the input list. The input list. The list of transformed elements. let inputs = [ "a"; "bbb"; "cc" ] inputs |> List.map (fun x -> x.Length) Evaluates to [ 1; 3; 2 ] Returns the last element of the list. Return None if no such element exists. The input list. The last element of the list or None. [ "pear"; "banana" ] |> List.tryLast Evaluates to Some "banana" [ ] |> List.tryLast Evaluates to None Returns the length of the list. The input list. The length of the list. The notation array.Length is preferred. let inputs = [ "a"; "b"; "c" ] inputs |> List.length Evaluates to 3 Returns the last element of the list. The input list. The last element of the list. Thrown when the input does not have any elements. [ "pear"; "banana" ] |> List.last Evaluates to banana [ ] |> List.last Throws ArgumentException Applies the given function to two collections simultaneously. The collections must have identical sizes. The integer passed to the function indicates the index of the element. The function to apply to a pair of elements from the input lists along with their index. The first input list. The second input list. let inputs1 = [ "a"; "b"; "c" ] let inputs2 = [ "banana"; "pear"; "apple" ] (inputs1, inputs2) ||> List.iteri2 (fun i s1 s2 -> printfn "Index %d: %s - %s" i s1 s2) Evaluates to unit and prints Index 0: a - banana Index 1: b - pear Index 2: c - apple in the console. Applies the given function to each element of the collection. The integer passed to the function indicates the index of the element. The function to apply to the elements of the list along with their index. The input list. let inputs = [ "a"; "b"; "c" ] inputs |> List.iteri (fun i v -> printfn "{i}: {v}") Evaluates to unit and prints 0: a 1: b 2: c in the console. Applies the given function to two collections simultaneously. The collections must have identical sizes. The function to apply to pairs of elements from the input lists. The first input list. The second input list. let inputs1 = [ "a"; "b"; "c" ] let inputs2 = [ 1; 2; 3 ] (inputs1, inputs2) ||> List.iter2 (printfn "%s: %i") Evaluates to unit and prints a: 1 b: 2 c: 3 in the console. Applies the given function to each element of the collection. The function to apply to elements from the input list. The input list. let inputs = [ "a"; "b"; "c" ] inputs |> List.iter (printfn "%s") Evaluates to unit and prints a b c in the console. Indexes into the list. The first element has index 0. The index to retrieve. The input list. The value at the given index. Thrown when the index is negative or the input list does not contain enough elements. let inputs = [ "a"; "b"; "c" ] inputs |> List.item 1 Evaluates to "b" let inputs = [ "a"; "b"; "c" ] inputs |> List.item 4 Throws ArgumentException Returns true if the list contains no elements, false otherwise. The input list. True if the list is empty. [ ] |> List.isEmpty Evaluates to true [ "pear"; "banana" ] |> List.isEmpty Evaluates to false Creates a list by calling the given generator on each index. The length of the list to generate. The function to generate an element from an index. Thrown when the input length is negative. The list of generated elements. List.init 4 (fun v -> v + 5) Evaluates to [5; 6; 7; 8] List.init -5 (fun v -> v + 5) Throws ArgumentException Returns a new list whose elements are the corresponding elements of the input list paired with the index (from 0) of each element. The input list. The list of indexed elements. let inputs = ["a"; "b"; "c"] inputs |> List.indexed Evaluates to [(0, "a"); (1, "b"); (2, "c")] Returns the first element of the list. The input list. Thrown when the list is empty. The first element of the list. let inputs = ["banana"; "pear"] inputs |> List.head Evaluates to banana [] |> List.head Throws ArgumentException Applies a key-generating function to each element of a list and yields a list of unique keys. Each unique key contains a list of all elements that match to this key. A function that transforms an element of the list into a comparable key. The input list. The result list. let inputs = [1; 2; 3; 4; 5] inputs |> List.groupBy (fun n -> n % 2) Evaluates to [(1, [1; 3; 5]); (0, [2; 4])] Tests if all corresponding elements of the collection satisfy the given predicate pairwise. The predicate is applied to matching elements in the two collections up to the lesser of the two lengths of the collections. If any application returns false then the overall result is false and no further elements are tested. Otherwise, if one collection is longer than the other then the exception is raised. Otherwise, true is returned. The function to test the input elements. The first input list. The second input list. Thrown when the input lists differ in length. True if all of the pairs of elements satisfy the predicate. let inputs1 = [1; 2; 3] let inputs2 = [1; 2; 3] (inputs1, inputs2) ||> List.forall2 (=) Evaluates to true. let items1 = [2017; 1; 1] let items2 = [2019; 19; 8] (items1, items2) ||> List.forall2 (=) Evaluates to false. let items1 = [1; 2; 3] let items2 = [1; 2] (items1, items2) ||> List.forall2 (=) Throws ArgumentException. Tests if all elements of the collection satisfy the given predicate. The predicate is applied to the elements of the input list. If any application returns false then the overall result is false and no further elements are tested. Otherwise, true is returned. The function to test the input elements. The input list. True if all of the elements satisfy the predicate. let isEven a = a % 2 = 0 [2; 42] |> List.forall isEven // evaluates to true [1; 2] |> List.forall isEven // evaluates to false Applies a function to corresponding elements of two collections, threading an accumulator argument through the computation. The collections must have identical sizes. If the input function is f and the elements are i0...iN and j0...jN then computes f i0 j0 (...(f iN jN s)). The function to update the state given the input elements. The first input list. The second input list. The initial state. The final state value. Count the positives, negatives and accumulate some text from back to front: type Count = { Positive: int Negative: int Text: string } let inputs1 = [ -1; -2; -3 ] let inputs2 = [ 3; 2; 1 ] let initialState = {Positive = 0; Negative = 0; Text = ""} (inputs1, inputs2, initialState) |||> List.foldBack2 (fun a b acc -> let text = acc.Text + "(" + string a + "," + string b + ") " if a + b >= 0 then { acc with Positive = acc.Positive + 1 Text = text } else { acc with Negative = acc.Negative + 1 Text = text } ) Evaluates to { Positive = 2 Negative = 1 Text = "(-3,1) (-2,2) (-1,3) " } Note acc is a commonly used abbreviation for "accumulator". Applies a function to each element of the collection, starting from the end, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f i0 (...(f iN s)). The function to update the state given the input elements. The input list. The initial state. The state object after the folding function is applied to each element of the list. Making the sum of squares for the first 5 natural numbers ([1..5], 0) ||> List.foldBack (fun v acc -> acc + v * v) // evaluates 55 Note acc is a commonly used abbreviation for "accumulator". Shopping for fruits hungry, you tend to take more of each as the hunger grows type Fruit = Apple | Pear | Orange type BagItem = { fruit: Fruit; quantity: int } let takeMore fruit (previous: BagItem list) = let toTakeThisTime = match previous with | bagItem :: otherBagItems -> bagItem.quantity + 1 | [] -> 1 { fruit = fruit; quantity = toTakeThisTime } :: previous let input = [ Apple; Pear; Orange ] (input, []) ||> List.foldBack takeMore Evaluates to [{ fruit = Apple; quantity = 3 } { fruit = Pear; quantity = 2 } { fruit = Orange; quantity = 1 }] Applies a function to corresponding elements of two collections, threading an accumulator argument through the computation. The collections must have identical sizes. If the input function is f and the elements are i0...iN and j0...jN then computes f (... (f s i0 j0)...) iN jN. The function to update the state given the input elements. The initial state. The first input list. The second input list. The final state value. Count the number of times the coins match: type CoinToss = Head | Tails let inputs1 = [Tails; Head; Tails] let inputs2 = [Tails; Head; Head] (0, inputs1, inputs2) |||> List.fold2 (fun acc input1 input2 -> match (input1, input2) with | Head, Head -> acc + 1 | Tails, Tails -> acc + 1 | _ -> acc) Evaluates to 2. Note acc is a commonly used abbreviation for "accumulator". Applies a function to each element of the collection, threading an accumulator argument through the computation. Take the second argument, and apply the function to it and the first element of the list. Then feed this result into the function along with the second element and so on. Return the final result. If the input function is f and the elements are i0...iN then computes f (... (f s i0) i1 ...) iN. The function to update the state given the input elements. The initial state. The input list. The final state value. Making the sum of squares for the first 5 natural numbers (0, [1..5]) ||> List.fold (fun s v -> s + v * v) // evaluates 55 Shopping for fruits hungry, you tend to take more of each as the hunger grows type Fruit = Apple | Pear | Orange type BagItem = { fruit: Fruit; quantity: int } let takeMore (previous: BagItem list) fruit = let toTakeThisTime = match previous with | bagItem :: otherBagItems -> bagItem.quantity + 1 | [] -> 1 { fruit = fruit; quantity = toTakeThisTime } :: previous let inputs = [ Apple; Pear; Orange ] ([], inputs) ||> List.fold takeMore Evaluates to [{ fruit = Orange; quantity = 3 } { fruit = Pear; quantity = 2 } { fruit = Apple; quantity = 1 }] Returns a new collection containing only the elements of the collection for which the given predicate returns "true" The function to test the input elements. The input list. A list containing only the elements that satisfy the predicate. let input = [1, "Luke"; 2, "Kirk"; 3, "Kenobi"; 4, "Spock"] let isEven x = 0 = x % 2 let isComingFromStarTrek (x,_) = isEven x input |> List.filter isComingFromStarTrek Evaluates to [(2, "Kirk"); (4, "Spock")] Returns the index of the last element in the list that satisfies the given predicate. Raises KeyNotFoundException if no such element exists. The function to test the input elements. The input list. Thrown if the predicate evaluates to false for all the elements of the list. The index of the last element that satisfies the predicate. let isEven x = 0 = x % 2 let isGreaterThan x y = y > x let input = [1, "Luke"; 2, "Kirk"; 3, "Spock"; 4, "Kenobi"] input |> List.findIndexBack (fun (x,_) -> isEven x) // evaluates 3 input |> List.findIndexBack (fun (x,_) -> x |> isGreaterThan 6) // raises an exception Returns the index of the first element in the list that satisfies the given predicate. Raises KeyNotFoundException if no such element exists. The function to test the input elements. The input list. Thrown if the predicate evaluates to false for all the elements of the list. The index of the first element that satisfies the predicate. let isEven x = 0 = x % 2 let isGreaterThan x y = y > x let input = [1, "Luke"; 2, "Kirk"; 3, "Spock"; 4, "Kenobi"] input |> List.findIndex (fun (x,_) -> isEven x) // evaluates 1 input |> List.findIndex (fun (x,_) -> x |> isGreaterThan 6) // raises an exception Returns the last element for which the given function returns True. Raises KeyNotFoundException if no such element exists. The function to test the input elements. The input list. Thrown if the predicate evaluates to false for all the elements of the list. The last element that satisfies the predicate. let isEven x = 0 = x % 2 let isGreaterThan x y = y > x let input = [1, "Luke"; 2, "Kirk"; 3, "Spock"; 4, "Kenobi"] input |> List.findBack (fun (x,_) -> isEven x) // evaluates (4, "Kenobi") input |> List.findBack (fun (x,_) -> x |> isGreaterThan 6) // raises an exception Returns the first element for which the given function returns True. Raises KeyNotFoundException if no such element exists. The function to test the input elements. The input list. Thrown if the predicate evaluates to false for all the elements of the list. The first element that satisfies the predicate. let isEven x = 0 = x % 2 let isGreaterThan x y = y > x let input = [1, "Luke"; 2, "Kirk"; 3, "Spock"; 4, "Kenobi"] input |> List.find (fun (x,_) -> isEven x) // evaluates (2, "Kirk") input |> List.find (fun (x,_) -> x |> isGreaterThan 6) // raises an exception Tests if any pair of corresponding elements of the lists satisfies the given predicate. The predicate is applied to matching elements in the two collections up to the lesser of the two lengths of the collections. If any application returns true then the overall result is true and no further elements are tested. Otherwise, if one collections is longer than the other then the exception is raised. Otherwise, false is returned. The function to test the input elements. The first input list. The second input list. Thrown when the input lists differ in length. True if any pair of elements satisfy the predicate. Check if the sum of pairs (from 2 different lists) have at least one even number let anEvenSum a b = 0 = (a + b) % 2 ([1..4], [2..5]) ||> List.exists2 anEvenSum // evaluates false ([1..4], [2;4;5;6]) ||> List.exists2 anEvenSum // evaluates true Tests if any element of the list satisfies the given predicate. The predicate is applied to the elements of the input list. If any application returns true then the overall result is true and no further elements are tested. Otherwise, false is returned. The function to test the input elements. The input list. True if any element satisfies the predicate. let input = [1, "Kirk"; 2, "Spock"; 3, "Kenobi"] input |> List.exists (fun x -> x = (3, "Kenobi")) // evaluates true input |> List.exists (fun (n, name) -> n > 5) // evaluates false Returns the only element of the list or None if it is empty or contains more than one element. The input list. The only element of the list or None. [1] |> List.tryExactlyOne // evaluates Some 1 [1;2] |> List.tryExactlyOne // evaluates None ([] : int list) |> List.tryExactlyOne // evaluates None Returns the only element of the list. The input list. The only element of the list. Thrown when the input does not have precisely one element. ["the chosen one"] |> List.exactlyOne // evaluates "the chosen one" let input : string list = [] input |> List.exactlyOne Will throw the exception: System.ArgumentException: The input sequence was empty [1..5] |> List.exactlyOne Will throw the exception: System.ArgumentException: The input sequence contains more than one element Returns a new list with the distinct elements of the input list which do not appear in the itemsToExclude sequence, using generic hash and equality comparisons to compare values. A sequence whose elements that also occur in the input list will cause those elements to be removed from the result. A list whose elements that are not also in itemsToExclude will be returned. A list that contains the distinct elements of list that do not appear in itemsToExclude. Thrown when itemsToExclude is null. let input = [1, "Kirk"; 2, "Spock"; 3, "Kenobi"] input |> List.except [3, "Kenobi"] Evaluates to [(1, "Kirk"); (2, "Spock")]. [0..10] |> List.except [1..5] // evaluates [0; 6; 7; 8; 9; 10] [1..5] |> List.except [0..10] // evaluates [] Returns an empty list of the given type. Splits the input list into at most count chunks. The maximum number of chunks. The input list. The list split into chunks. Thrown when count is not positive. [1..10] |> List.splitInto 2 Evaluates to [[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]]. [1..10] |> List.splitInto 4 Evaluates to [[1; 2; 3]; [4; 5; 6]; [7; 8]; [9; 10]]. Applies a key-generating function to each element of a list and returns a list yielding unique keys and their number of occurrences in the original list. A function transforming each item of the input list into a key to be compared against the others. The input list. The result list. Counting the number of occurrences of chars let input = ['H'; 'a'; 'p'; 'p'; 'y'] input |> List.countBy id Evaluates [('H', 1); ('a', 1); ('p', 2); ('y', 1)] Returns a list that contains no duplicate entries according to the generic hash and equality comparisons on the keys returned by the given key-generating function. If an element occurs multiple times in the list then the later occurrences are discarded. A function transforming the list items into comparable keys. The input list. The result list. let isEven x = 0 = x % 2 let input = [6;1;2;3;1;4;5;5] input |> List.distinctBy isEven // evaluates [6; 1] Returns a list that contains no duplicate entries according to generic hash and equality comparisons on the entries. If an element occurs multiple times in the list then the later occurrences are discarded. The input list. The result list. let input = [6;1;2;3;1;4;5;5] input |> List.distinct Evaluates to [6; 1; 2; 3; 4; 5]. Tests if the list contains the specified element. The value to locate in the input list. The input list. True if the input list contains the specified element; false otherwise. [1..9] |> List.contains 0 Evaluates to false. [1..9] |> List.contains 3 Evaluates to true. let input = [1, "SpongeBob"; 2, "Patrick"; 3, "Squidward"; 4, "Mr. Krabs"] input |> List.contains (2, "Patrick") Evaluates to true. let input = [1, "SpongeBob"; 2, "Patrick"; 3, "Squidward"; 4, "Mr. Krabs"] input |> List.contains (22, "Patrick") Evaluates to false. Returns a new list that contains the elements of each of the lists in order. The input sequence of lists. The resulting concatenated list. let input = [ [1;2] [3;4;5] [6;7;8;9] ] input |> List.concat // evaluates [1; 2; 3; 4; 5; 6; 7; 8; 9] Compares two lists using the given comparison function, element by element. A function that takes an element from each list and returns an int. If it evaluates to a non-zero value iteration is stopped and that value is returned. The first input list. The second input list. Returns the first non-zero result from the comparison function. If the first list has a larger element, the return value is always positive. If the second list has a larger element, the return value is always negative. When the elements are equal in the two lists, 1 is returned if the first list is longer, 0 is returned if they are equal in length, and -1 is returned when the second list is longer. let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 10] let input2 = [1; 10] (input1, input2) ||> List.compareWith closerToNextDozen Evaluates to 0 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 5] let input2 = [1; 8] (input1, input2) ||> List.compareWith closerToNextDozen Evaluates to -1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 11] let input2 = [1; 13] (input1, input2) ||> List.compareWith closerToNextDozen Evaluates to 1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1; 2] let input2 = [1] (input1, input2) ||> List.compareWith closerToNextDozen Evaluates to 1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [1] let input2 = [1; 2] (input1, input2) ||> List.compareWith closerToNextDozen Evaluates to -1 For each element of the list, applies the given function. Concatenates all the results and returns the combined list. The function to transform each input element into a sublist to be concatenated. The input list. The concatenation of the transformed sublists. For each positive number in the array we are generating all the previous positive numbers [1..4] |> List.collect (fun x -> [1..x]) The sample evaluates to [1; 1; 2; 1; 2; 3; 1; 2; 3; 4] (added extra spaces for easy reading) Divides the input list into lists (chunks) of size at most chunkSize. Returns a new list containing the generated lists (chunks) as its elements. Returns an empty list when the input list is empty. The maximum size of each chunk. The input list. The list divided into chunks. Thrown when chunkSize is not positive. [ 1..10 ] |> List.chunkBySize 3 Evaluates to [ [ 1; 2; 3 ] [ 4; 5; 6 ] [ 7; 8; 9 ] [ 10 ] ] [ 1..5 ] |> List.chunkBySize 10 Evaluates to [ [ 1; 2; 3; 4; 5 ] ] Applies a function to each element in a list and then returns a list of values v where the applied function returned Some(v). Returns an empty list when the input list is empty or when the applied chooser function returns None for all elements. The function to be applied to the list elements. The input list. The resulting list comprising the values v where the chooser function returned Some(x). Using the identity function id (is defined like fun x -> x): let input1 = [ Some 1; None; Some 3; None ] input1 |> List.choose id Evaluates to [ 1; 3 ] type Happiness = | AlwaysHappy | MostOfTheTimeGrumpy type People = { Name: string; Happiness: Happiness } let takeJustHappyPersons person = match person.Happiness with | AlwaysHappy -> Some person.Name | MostOfTheTimeGrumpy -> None let candidatesForTheTrip = [ { Name = "SpongeBob" Happiness = AlwaysHappy } { Name = "Patrick" Happiness = AlwaysHappy } { Name = "Squidward" Happiness = MostOfTheTimeGrumpy } ] candidatesForTheTrip |> List.choose takeJustHappyPersons Evaluates to [ "SpongeBob"; "Patrick" ] let input3: int option list = [] input3 |> List.choose id Evaluates to: empty list let input4: string option list = [None; None] input4 |> List.choose id Evaluates to empty list Using the identity function id (is defined like fun x -> x): let input5 = [ Some 1; None; Some 3; None ] input5 |> List.choose id // evaluates [1; 3] Returns the average of values in a list generated by applying a function to each element of the list. The function to transform the list elements into the values to be averaged. The input list. Thrown when the list is empty. The resulting average. Calculate average age of persons by extracting their age from a record type. type People = { Name: string; Age: int } let getAgeAsFloat person = float person.Age let people = [ { Name = "Kirk"; Age = 26 } { Name = "Spock"; Age = 90 } { Name = "McCoy"; Age = 37 } ] people |> List.averageBy getAgeAsFloat Evaluates to 51.0 Returns the average of the values in a non-empty list. The input list. Thrown when the input list is empty. The resulting average. [1.0 .. 9.0] |> List.average Evaluates to 5.0 Returns a new list that contains the elements of the first list followed by elements of the second list. The first input list. The second input list. The resulting list. List.append [ 1..3 ] [ 4..7 ] [ 4..7 ] |> List.append [ 1..3 ] Evaluates to [ 1; 2; 3; 4; 5; 6; 7 ] Returns a new list that contains all pairings of elements from two lists. The first input list. The second input list. The resulting list of pairs. let people = [ "Kirk"; "Spock"; "McCoy" ] let numbers = [ 1; 2 ] people |> List.allPairs numbers Evaluates to [ (1, "Kirk"); (1, "Spock"); (1, "McCoy"); (2, "Kirk"); (2, "Spock"); (2, "McCoy") ] Contains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide. Returns a random sample of elements from the given array using the specified randomizer function, each element can be selected only once. The randomizer function, must return a float number from [0.0..1.0) range. The number of elements to return. The input array. An array of randomly selected elements from the input array. Thrown when the input array is null. Thrown when the input array is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input array. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomSampleBy Random.Shared.NextDouble 3 Can evaluate to [| 3; 1; 2 |]. Returns a random sample of elements from the given array with the specified Random instance, each element can be selected only once. The Random instance. The number of elements to return. The input array. An array of randomly selected elements from the input array. Thrown when the input array is null. Thrown when the random argument is null. Thrown when the input array is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input array. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomSampleWith Random.Shared 3 Can evaluate to [| 3; 1; 2 |]. Returns a random sample of elements from the given array, each element can be selected only once. The number of elements to return. The input array. An array of randomly selected elements from the input array. Thrown when the input array is null. Thrown when the input array is empty. Thrown when count is less than 0. Thrown when count is greater than the length of the input array. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomSample 3 Can evaluate to [| 3; 1; 2 |]. Returns an array of random elements from the given array using the specified randomizer function, each element can be selected multiple times. The randomizer function, must return a float number from [0.0..1.0) range. The number of elements to return. The input array. An array of randomly selected elements from the input array. Thrown when the input array is null. Thrown when the input array is empty. Thrown when count is less than 0. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomChoicesBy Random.Shared.NextDouble 3 Can evaluate to [| 3; 1; 3 |]. Returns an array of random elements from the given array with the specified Random instance, each element can be selected multiple times. The Random instance. The number of elements to return. The input array. An array of randomly selected elements from the input array. Thrown when the input array is null. Thrown when the random argument is null. Thrown when the input array is empty. Thrown when count is less than 0. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomChoicesWith Random.Shared 3 Can evaluate to [| 3; 1; 3 |]. Returns an array of random elements from the given array, each element can be selected multiple times. The number of elements to return. The input array. An array of randomly selected elements from the input array. Thrown when the input array is null. Thrown when the input array is empty. Thrown when count is less than 0. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomChoices 3 Can evaluate to [| 3; 1; 3 |]. Returns a random element from the given array using the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The input array. A randomly selected element from the input array. Thrown when the input array is null. Thrown when the input array is empty. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomChoiceBy Random.Shared.NextDouble Can evaluate to 3. Returns a random element from the given array with the specified Random instance. The Random instance. The input array. A randomly selected element from the input array. Thrown when the input array is null. Thrown when the random argument is null. Thrown when the input array is empty. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomChoiceWith Random.Shared Can evaluate to 3. Returns a random element from the given array. The input array. A randomly selected element from the input array. Thrown when the input array is null. Thrown when the input array is empty. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomChoice Can evaluate to 3. Sorts input array in a random order using the specified randomizer function by mutating the array in-place. The randomizer function, must return a float number from [0.0..1.0) range. The input array. Thrown when the input array is null. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomShuffleInPlaceBy Random.Shared.NextDouble After evaluation array can contain [| 0; 2; 4; 3; 1 |]. Sorts input array in a random order with the specified Random instance by mutating the array in-place. The input array. The Random instance. Thrown when the input array is null. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomShuffleInPlaceWith Random.Shared After evaluation array can contain [| 0; 2; 4; 3; 1 |]. Sorts input array in a random order by mutating the array in-place. The input array. Thrown when the input array is null. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomShuffleInPlace After evaluation array can contain [| 0; 2; 4; 3; 1 |]. Return a new array shuffled in a random order using the specified randomizer function. The randomizer function, must return a float number from [0.0..1.0) range. The input array. The result array. Thrown when the input array is null. Thrown when the randomizer function returns a value outside the range [0, 1). let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomShuffleBy Random.Shared.NextDouble Can evaluate to [| 0; 2; 4; 3; 1 |]. Return a new array shuffled in a random order with the specified Random instance. The Random instance. The input array. The result array. Thrown when the input array is null. Thrown when the random argument is null. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomShuffleWith Random.Shared Can evaluate to [| 0; 2; 4; 3; 1 |]. Return a new array shuffled in a random order. The input array. The result array. Thrown when the input array is null. let inputs = [| 0; 1; 2; 3; 4 |] inputs |> Array.randomShuffle Can evaluate to [| 0; 2; 4; 3; 1 |]. Return a new array with new items inserted before the given index. The index where the items should be inserted. The values to insert. The input array. A new array (even if values is empty). Thrown when index is below 0 or greater than source.Length. let inputs = [| 0; 1; 2 |] inputs |> Array.insertManyAt 1 [8; 9] Evaluates to [| 0; 8; 9; 1; 2 |]. Return a new array with a new item inserted before the given index. The index where the item should be inserted. The value to insert. The input array. The result array. Thrown when index is below 0 or greater than source.Length. let inputs = [| 0; 1; 2 |] inputs |> Array.insertAt 1 9 Evaluates to [| 0; 9; 1; 2 |]. Return a new array with the item at a given index set to the new value. The index of the item to be replaced. The new value. The input array. The result array. Thrown when index is outside 0..source.Length - 1 let inputs = [| 0; 1; 2 |] inputs |> Array.updateAt 1 9 Evaluates to [| 0; 9; 2 |]. Return a new array with the number of items starting at a given index removed. The index of the item to be removed. The number of items to remove. The input array. The result array. Thrown when index is outside 0..source.Length - count let inputs = [| 0; 1; 2; 3 |] inputs |> Array.removeManyAt 1 2 Evaluates to [| 0; 3 |]. Return a new array with the item at a given index removed. The index of the item to be removed. The input array. The result array. Thrown when index is outside 0..source.Length - 1 let inputs = [| 0; 1; 2 |] inputs |> Array.removeAt 1 Evaluates to [| 0; 2 |]. Combines three arrays into an array of pairs. The three arrays must have equal lengths, otherwise an ArgumentException is raised. The first input array. The second input array. The third input array. Thrown when any of the input arrays are null. Thrown when the input arrays differ in length. The array of tupled elements. let numbers = [| 1; 2 |] let names = [| "one"; "two" |] let roman = [| "I"; "II" |] Array.zip3 numbers names roman Evaluates to [|(1, "one", "I"); (2, "two", "II")|]. Combines the two arrays into an array of pairs. The two arrays must have equal lengths, otherwise an ArgumentException is raised. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. The array of tupled elements. let numbers = [|1; 2|] let names = [|"one"; "two"|] Array.zip numbers names Evaluates to [| (1, "one"); (2, "two") |]. Returns an array of sliding windows containing elements drawn from the input array. Each window is returned as a fresh array. The number of elements in each window. The input array. The result array. Thrown when the input array is null. Thrown when windowSize is not positive. let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.windowed 3 Evaluates to [|[|1; 2; 3|]; [|2; 3; 4|]; [|3; 4; 5|]|] Returns a new array containing only the elements of the array for which the given predicate returns "true". The function to test the input elements. The input array. An array containing the elements for which the given predicate returns true. Thrown when the input array is null. This is identical to Array.filter. Select only the even numbers: let inputs = [| 1; 2; 3; 4 |] inputs |> Array.where (fun elm -> elm % 2 = 0) Evaluates to [| 2; 4 |] Splits an array of triples into three arrays. The input array. The tuple of three arrays. Thrown when the input array is null. let inputs = [| (1, "one", "I"); (2, "two", "II") |] let numbers, names, roman = inputs |> Array.unzip3 Evaluates numbers to [|1; 2|], names to [|"one"; "two"|] and roman to [|"I"; "II"|]. Splits an array of pairs into two arrays. The input array. The two arrays. Thrown when the input array is null. let inputs = [| (1, "one"); (2, "two") |] let numbers, names = inputs |> Array.unzip Evaluates numbers to [|1; 2|] and names to [|"one"; "two"|]. Returns an array that contains the elements generated by the given computation. The generator is repeatedly called to build the list until it returns `None`. The given initial state argument is passed to the element generator. A function that takes in the current state and returns an option tuple of the next element of the array and the next state value. The initial state value. The result array. 1 |> Array.unfold (fun state -> if state > 100 then None else Some (state, state * 2)) Evaluates to [| 1; 2; 4; 8; 16; 32; 64 |] Returns the index of the last element in the array that satisfies the given predicate. The function to test the input elements. The input array. Thrown when the input array is null. The index of the last element that satisfies the predicate, or None. Try to find the index of the first even number from the back: let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.tryFindIndexBack (fun elm -> elm % 2 = 0) Evaluates to Some 3 Try to find the index of the first even number from the back: let inputs = [| 1; 3; 5; 7 |] inputs |> Array.tryFindIndexBack (fun elm -> elm % 2 = 0) Evaluates to None Tries to find the nth element in the array. Returns None if index is negative or the input array does not contain enough elements. The index of element to retrieve. The input array. The nth element of the array or None. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.tryItem 1 Evaluates to Some "b". let inputs = [| "a"; "b"; "c" |] inputs |> Array.tryItem 4 Evaluates to None. Returns the index of the first element in the array that satisfies the given predicate. The function to test the input elements. The input array. Thrown when the input array is null. The index of the first element that satisfies the predicate, or None. Try to find the index of the first even number: let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to Some 1 Try to find the index of the first even number: let inputs = [| 1; 3; 5; 7 |] inputs |> Array.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to None Returns the last element for which the given function returns True. Return None if no such element exists. The function to test the input elements. The input array. Thrown when the input array is null. The last element that satisfies the predicate, or None. Try to find the first even number from the back: let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.tryFindBack (fun elm -> elm % 2 = 0) Evaluates to Some 4 Try to find the first even number from the back: let inputs = [| 1; 5; 3 |] inputs |> Array.tryFindBack (fun elm -> elm % 2 = 0) Evaluates to None Returns the first element for which the given function returns True. Return None if no such element exists. The function to test the input elements. The input array. The first element that satisfies the predicate, or None. Thrown when the input array is null. Try to find the first even number: let inputs = [| 1; 2; 3 |] inputs |> Array.tryFind (fun elm -> elm % 2 = 0) Evaluates to Some 2 Try to find the first even number: let inputs = [| 1; 5; 3 |] inputs |> Array.tryFind (fun elm -> elm % 2 = 0) Evaluates to None Returns at most N elements in a new array. The maximum number of items to return. The input array. The result array. Thrown when the input array is null. let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.truncate 2 Evaluates to [| "a"; "b" |] let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.truncate 6 Evaluates to [| "a"; "b"; "c"; "d" |] let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.truncate 0 Evaluates to [| |]. Returns the transpose of the given sequence of arrays. The input sequence of arrays. The transposed array. Thrown when the input sequence is null. Thrown when the input arrays differ in length. let inputs = [| [| 10; 20; 30 |] [| 11; 21; 31 |] |] inputs |> Array.transpose Evaluates to [|[|10; 11|]; [|20; 21|]; [|30; 31|]|]. Views the given array as a sequence. The input array. The sequence of array elements. Thrown when the input array is null. let inputs = [| 1; 2; 5 |] inputs |> Array.toSeq Evaluates to seq { 1; 2; 5 }. Builds a list from the given array. The input array. The list of array elements. Thrown when the input array is null. let inputs = [| 1; 2; 5 |] inputs |> Array.toList Evaluates to [ 1; 2; 5 ]. Returns a new array containing the elements of the original except the first element. The input array. Thrown when the array is empty. Thrown when the input array is null. A new array containing the elements of the original except the first element. let inputs = [| "a"; "bb"; "ccc" |] inputs |> Array.tail Evaluates to [| "bb"; "ccc" |] Returns an array that contains all elements of the original array while the given predicate returns True, and then returns no further elements. A function that evaluates to false when no more items should be returned. The input array. The result array. Thrown when the input array is null. let inputs = [| "a"; "bb"; "ccc"; "d" |] inputs |> Array.takeWhile (fun x -> x.Length < 3) Evaluates to [| "a"; "bb" |] Returns the first N elements of the array. Throws InvalidOperationException if the count exceeds the number of elements in the array. Array.truncate returns as many items as the array contains instead of throwing an exception. The number of items to take. The input array. The result array. Thrown when the input array is null. Thrown when the input array is empty. Thrown when count exceeds the number of elements in the list. let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.take 2 Evaluates to [| "a"; "b" |] let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.take 6 Throws InvalidOperationException. let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.take 0 Evaluates to [| |]. Returns the sum of the results generated by applying the function to each element of the array. The function to transform the array elements into the type to be summed. The input array. The resulting sum. Thrown when the input array is null. let input = [| "aa"; "bbb"; "cc" |] input |> Array.sumBy (fun s -> s.Length) Evaluates to 7. Returns the sum of the elements in the array. The input array. The resulting sum. Thrown when the input array is null. let input = [| 1; 5; 3; 2 |] input |> Array.sum Evaluates to 11. Sorts the elements of an array, in descending order, using the given projection for the keys and returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to transform array elements into the type that is compared. The input array. The sorted array. let input = [| "a"; "bbb"; "cccc"; "dd" |] input |> Array.sortByDescending (fun s -> s.Length) Evaluates to [|"cccc"; "bbb"; "dd"; "a"|]. Sorts the elements of an array, in descending order, returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The input array. The sorted array. let input = [| 8; 4; 3; 1; 6; 1 |] input |> Array.sortDescending Evaluates to [| 8; 6; 4; 3; 1; 1 |]. Splits an array into two arrays, at the given index. The index at which the array is split. The input array. The two split arrays. Thrown when the input array is null. Thrown when split index exceeds the number of elements in the array. let input = [| 8; 4; 3; 1; 6; 1 |] let front, back = input |> Array.splitAt 3 Evaluates front to [|8; 4; 3|] and back to [|1; 6; 1|]. Sorts the elements of an array by mutating the array in-place, using the given comparison function. Elements are compared using . The input array. Thrown when the input array is null. let array = [| 8; 4; 3; 1; 6; 1 |] Array.sortInPlace array After evaluation array contains [| 1; 1; 3; 4; 6; 8 |]. Sorts the elements of an array by mutating the array in-place, using the given comparison function as the order. The function to compare pairs of array elements. The input array. Thrown when the input array is null. The following sorts entries using a comparison function that compares string lengths then index numbers: let compareEntries (n1: int, s1: string) (n2: int, s2: string) = let c = compare s1.Length s2.Length if c <> 0 then c else compare n1 n2 let array = [| (0,"aa"); (1,"bbb"); (2,"cc"); (3,"dd") |] array |> Array.sortInPlaceWith compareEntries After evaluation array contains [|(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")|]. Sorts the elements of an array by mutating the array in-place, using the given projection for the keys. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to transform array elements into the type that is compared. The input array. Thrown when the input array is null. let array = [| "a"; "bbb"; "cccc"; "dd" |] array |> Array.sortInPlaceBy (fun s -> s.Length) After evaluation array contains [|"a"; "dd"; "bbb"; "cccc"|]. Sorts the elements of an array, using the given comparison function as the order, returning a new array. This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to compare pairs of array elements. The input array. The sorted array. Thrown when the input array is null. Sort an array of pairs using a comparison function that compares string lengths then index numbers: let compareEntries (n1: int, s1: string) (n2: int, s2: string) = let c = compare s1.Length s2.Length if c <> 0 then c else compare n1 n2 let input = [| (0,"aa"); (1,"bbb"); (2,"cc"); (3,"dd") |] input |> Array.sortWith compareEntries Evaluates to [|(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")|]. Sorts the elements of an array, using the given projection for the keys and returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to transform array elements into the type that is compared. The input array. The sorted array. Thrown when the input array is null. let input = [| "a"; "bbb"; "cccc"; "dd" |] input |> Array.sortBy (fun s -> s.Length) Evaluates to [|"a"; "dd"; "bbb"; "cccc"|]. Sorts the elements of an array, returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The input array. The sorted array. Thrown when the input array is null. let input = [| 8; 4; 3; 1; 6; 1 |] Array.sort input Evaluates to [| 1; 1; 3; 4; 6; 8 |]. Builds a new array that contains the given subrange specified by starting index and length. The input array. The index of the first element of the sub array. The length of the sub array. The created sub array. Thrown when the input array is null. Thrown when either startIndex or count is negative, or when there aren't enough elements in the input array. Slicing syntax is generally preferred, e.g. let input = [| 0; 1; 2; 3; 4; 5 |] input.[2..4] let input = [| 0; 1; 2; 3; 4; 5 |] Array.sub input 2 3 Evaluates to [| 2; 3; 4 |]. Bypasses elements in an array while the given predicate returns True, and then returns the remaining elements in a new array. A function that evaluates an element of the array to a boolean value. The input array. The created sub array. Thrown when the input array is null. let inputs = [| "a"; "bbb"; "cc"; "d" |] inputs |> Array.skipWhile (fun x -> x.Length < 3) Evaluates to [|"bbb"; "cc"; "d"|] Builds a new array that contains the elements of the given array, excluding the first N elements. The number of elements to skip. If negative the full array will be returned as a copy. The input array. A copy of the input array, after removing the first N elements. Thrown when the input array is null. Thrown when count exceeds the number of elements in the array. let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.skip 2 Evaluates to [| "c"; "d" |] let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.skip 5 Throws ArgumentException. let inputs = [| "a"; "b"; "c"; "d" |] inputs |> Array.skip -1 Evaluates to [| "a"; "b"; "c"; "d" |]. Sets an element of an array. The input array. The input index. The input value. Thrown when the input array is null. Thrown when the index is negative or the input array does not contain enough elements. let inputs = [| "a"; "b"; "c" |] Array.set inputs 1 "B" After evaluation inputs contains [| "a"; "B"; "c" |] let inputs = [| "a"; "b"; "c" |] Array.set inputs 4 "d" Throws IndexOutOfRangeException Returns an array that contains one item only. The input item. The result array of one item. Array.singleton 7 Evaluates to [| 7 |]. Like foldBack, but return both the intermediary and final results. The function to update the state given the input elements. The input array. The initial state. The array of state values. Thrown when the input array is null. Apply a list charges from back to front, and collect the running balances as each is applied: type Charge = | In of int | Out of int let inputs = [| In 1; Out 2; In 3 |] (inputs, 0) ||> Array.scanBack (fun charge acc -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to [|2; 1; 3; 0|] by processing each input from back to front. Note 0 is the initial state, 3 the next state, 1 the next state, and 2 the final state. Like fold, but return the intermediary and final results. The function to update the state given the input elements. The initial state. The input array. The array of state values. Thrown when the input array is null. Apply a list charges and collect the running balances as each is applied: type Charge = | In of int | Out of int let inputs = [| In 1; Out 2; In 3 |] (0, inputs) ||> Array.scan (fun acc charge -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to [|0; 1; -1; 2|]. Note 0 is the initial state, 1 the next state, -1 the next state, and 2 the final state. Returns a new array with the elements in reverse order. The input array. The reversed array. Thrown when the input array is null. Array.rev [| 0; 1; 2 |] Evaluates to [| 2; 1; 0 |]. Creates an array by replicating the given initial value. The number of elements to replicate. The value to replicate The generated array. Thrown when count is negative. Array.replicate 3 "a" Evaluates to [| "a"; "a"; "a" |]. Applies a function to each element of the array, starting from the end, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f i0 (...(f iN-1 iN)). A function that takes in the next-to-last element of the list and the current accumulated result to produce the next accumulated result. The input array. Thrown when the input array is null. Thrown when the input array is empty. The final result of the reductions. let inputs = [| 1; 3; 4; 2 |] inputs |> Array.reduceBack (fun a b -> a + b * 10) Evaluates to 2431, by computing 1 + (3 + (4 + 2 * 10) * 10) * 10 Applies a function to each element of the array, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f (... (f i0 i1)...) iN. Raises ArgumentException if the array has size zero. The function to reduce a pair of elements to a single element. The input array. Thrown when the input array is null. Thrown when the input array is empty. The final result of the reductions. let inputs = [| 1; 3; 4; 2 |] inputs |> Array.reduce (fun a b -> a * 10 + b) Evaluates to 1342, by computing ((1 * 10 + 3) * 10 + 4) * 10 + 2 Returns an array with all elements permuted according to the specified permutation. The function that maps input indices to output indices. The input array. The output array. Thrown when the input array is null. Thrown when indexMap does not produce a valid permutation. let inputs = [| 1; 2; 3; 4 |] inputs |> Array.permute (fun x -> (x + 1) % 4) Evaluates to [|4; 1; 2; 3|]. Splits the collection into two collections, containing the elements for which the given predicate returns "true" and "false" respectively. The function to test the input elements. The input array. A pair of arrays. The first containing the elements the predicate evaluated to true, and the second containing those evaluated to false. Thrown when the input array is null. let inputs = [| 1; 2; 3; 4 |] inputs |> Array.partition (fun x -> x % 2 = 0) Evaluates to ([|2; 4|], [|1; 3|]). Returns an array of each element in the input array and its predecessor, with the exception of the first element which is only returned as the predecessor of the second element. The input array. The result array. Thrown when the input sequence is null. let inputs = [| 1; 2; 3; 4 |] inputs |> Array.pairwise Evaluates to [|(1, 2); (2, 3); (3, 4)|]. Builds a new array from the given enumerable object. The input sequence. The array of elements from the sequence. Thrown when the input sequence is null. let inputs = seq { 1; 2; 5 } inputs |> Array.ofSeq Evaluates to [| 1; 2; 5 |]. Builds an array from the given list. The input list. The array of elements from the list. let inputs = [ 1; 2; 5 ] inputs |> Array.ofList Evaluates to [| 1; 2; 5 |]. Returns the lowest of all elements of the array, compared via Operators.min on the function result. Throws ArgumentException for empty arrays. The function to transform the elements into a type supporting comparison. The input array. Thrown when the input array is null. Thrown when the input array is empty. The minimum element. let inputs = [| "aaa"; "b"; "cccc" |] inputs |> Array.minBy (fun s -> s.Length) Evaluates to "b" let inputs: string array= [| |] inputs |> Array.minBy (fun s -> s.Length) Throws System.ArgumentException. Returns the lowest of all elements of the array, compared via Operators.min. Throws ArgumentException for empty arrays The input array. Thrown when the input array is null. Thrown when the input array is empty. The minimum element. let inputs = [| 10; 12; 11 |] inputs |> Array.min Evaluates to 10 let inputs: int array= [| |] inputs |> Array.min Throws System.ArgumentException. Returns the greatest of all elements of the array, compared via Operators.max on the function result. Throws ArgumentException for empty arrays. The function to transform the elements into a type supporting comparison. The input array. Thrown when the input array is null. Thrown when the input array is empty. The maximum element. let inputs = [| "aaa"; "b"; "cccc" |] inputs |> Array.maxBy (fun s -> s.Length) Evaluates to "cccc" let inputs: string array= [| |] inputs |> Array.maxBy (fun s -> s.Length) Throws System.ArgumentException. Returns the greatest of all elements of the array, compared via Operators.max on the function result. Throws ArgumentException for empty arrays. The input array. Thrown when the input array is null. Thrown when the input array is empty. The maximum element. let inputs = [| 10; 12; 11 |] inputs |> Array.max Evaluates to 12 let inputs: int array= [| |] inputs |> Array.max Throws System.ArgumentException. Builds a new array whose elements are the results of applying the given function to each of the elements of the array. The integer index passed to the function indicates the index of element being transformed, starting at zero. The function to transform elements and their indices. The input array. The array of transformed elements. Thrown when the input array is null. let inputs = [| 10; 10; 10 |] inputs |> Array.mapi (fun i x -> i + x) Evaluates to [| 10; 11; 12 |] Builds a new collection whose elements are the results of applying the given function to the corresponding elements of the two collections pairwise, also passing the index of the elements. The two input arrays must have the same lengths, otherwise an ArgumentException is raised. The function to transform pairs of input elements and their indices. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. The array of transformed elements. let inputs1 = [| "a"; "bad"; "good" |] let inputs2 = [| 0; 2; 1 |] (inputs1, inputs2) ||> Array.mapi2 (fun i x y -> i, x[y]) Evaluates to [|(0, 'a'); (1, 'd'); (2, 'o')|] Builds a new collection whose elements are the results of applying the given function to the corresponding triples from the three collections. The three input arrays must have the same length, otherwise an ArgumentException is raised. The function to transform the pairs of the input elements. The first input array. The second input array. The third input array. Thrown when the input arrays differ in length. Thrown when any of the input arrays is null. The array of transformed elements. let inputs1 = [| "a"; "t"; "ti" |] let inputs2 = [| "l"; "h"; "m" |] let inputs3 = [| "l"; "e"; "e" |] (inputs1, inputs2, inputs3) |||> Array.map3 (fun x y z -> x + y + z) Evaluates to [| "all"; "the"; "time" |] Combines map and foldBack. Builds a new array whose elements are the results of applying the given function to each of the elements of the input array. The function is also used to accumulate a final value. The function to transform elements from the input array and accumulate the final value. The input array. The initial state. Thrown when the input array is null. The array of transformed elements, and the final accumulated value. Accumulate the charges from back to front, and double them as well type Charge = | In of int | Out of int let inputs = [| In 1; Out 2; In 3 |] let newCharges, balance = (inputs, 0) ||> Array.mapFoldBack (fun charge acc -> match charge with | In i -> In (i*2), acc + i | Out o -> Out (o*2), acc - o) Evaluates newCharges to [|In 2; Out 4; In 6|] and balance to 2. Combines map and fold. Builds a new array whose elements are the results of applying the given function to each of the elements of the input array. The function is also used to accumulate a final value. The function to transform elements from the input array and accumulate the final value. The initial state. The input array. Thrown when the input array is null. The array of transformed elements, and the final accumulated value. Accumulate the charges, and double them as well type Charge = | In of int | Out of int let inputs = [| In 1; Out 2; In 3 |] let newCharges, balance = (0, inputs) ||> Array.mapFold (fun acc charge -> match charge with | In i -> In (i*2), acc + i | Out o -> Out (o*2), acc - o) Evaluates newCharges to [|In 2; Out 4; In 6|] and balance to 2. Builds a new collection whose elements are the results of applying the given function to the corresponding elements of the two collections pairwise. The two input arrays must have the same lengths, otherwise an ArgumentException is raised. The function to transform the pairs of the input elements. The first input array. The second input array. Thrown when the input arrays differ in length. Thrown when either of the input arrays is null. The array of transformed elements. let inputs1 = [| "a"; "bad"; "good" |] let inputs2 = [| 0; 2; 1 |] (inputs1, inputs2) ||> Array.map2 (fun x y -> x[y]) Evaluates to [| 'a'; 'd'; 'o' |] Builds a new array whose elements are the results of applying the given function to each of the elements of the array. The function to transform elements of the array. The input array. The array of transformed elements. Thrown when the input array is null. let inputs = [| "a"; "bbb"; "cc" |] inputs |> Array.map (fun x -> x.Length) Evaluates to [| 1; 3; 2 |] Returns the last element of the array. Return None if no such element exists. The input array. The last element of the array or None. Thrown when the input sequence is null. [| "pear"; "banana" |] |> Array.tryLast Evaluates to Some "banana" [| |] |> Array.tryLast Evaluates to None Returns the length of an array. You can also use property arr.Length. The input array. The length of the array. The notation array.Length is preferred. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.length Evaluates to 3 Gets an element from an array. The input index. The input array. The value of the array at the given index. Normally the syntax array[index] is preferred. Thrown when the input array is null. Thrown when the index is negative or the input array does not contain enough elements. let inputs = [| "a"; "b"; "c" |] inputs |> Array.item 1 Evaluates to "b" let inputs = [| "a"; "b"; "c" |] inputs |> Array.item 4 Throws ArgumentException Returns the last element of the array. The input array. The last element of the array. Thrown when the input array is null. Thrown when the input does not have any elements. [| "pear"; "banana" |] |> Array.last Evaluates to banana [| |] |> Array.last Throws ArgumentException Applies the given function to pair of elements drawn from matching indices in two arrays, also passing the index of the elements. The two arrays must have the same lengths, otherwise an ArgumentException is raised. The function to apply to each index and pair of elements. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. let inputs1 = [| "a"; "b"; "c" |] let inputs2 = [| "banana"; "pear"; "apple" |] (inputs1, inputs2) ||> Array.iteri2 (fun i s1 s2 -> printfn "Index {i}: {s1} - {s2}") Evaluates to unit and prints Index 0: a - banana Index 1: b - pear Index 2: c - apple in the console. Applies the given function to each element of the array. The integer passed to the function indicates the index of element. The function to apply to each index and element. The input array. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.iteri (fun i v -> printfn "{i}: {v}") Evaluates to unit and prints 0: a 1: b 2: c in the console. Applies the given function to pair of elements drawn from matching indices in two arrays. The two arrays must have the same lengths, otherwise an ArgumentException is raised. The function to apply. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. let inputs1 = [| "a"; "b"; "c" |] let inputs2 = [| 1; 2; 3 |] (inputs1, inputs2) ||> Array.iter2 (printfn "%s: %i") Evaluates to unit and prints a: 1 b: 2 c: 3 in the console. Applies the given function to each element of the array. The function to apply. The input array. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.iter (printfn "%s") Evaluates to unit and prints a b c in the console. Returns true if the given array is empty, otherwise false. The input array. True if the array is empty. Thrown when the input array is null. [| |] |> Array.isEmpty Evaluates to true [| "pear"; "banana" |] |> Array.isEmpty Evaluates to false Creates an array where the entries are initially the default value Unchecked.defaultof<'T>. The length of the array to create. The created array. Thrown when count is negative. let arr : int array = Array.zeroCreate 4 Evaluates to [| 0; 0; 0; 0 |] Creates an array given the dimension and a generator function to compute the elements. The number of elements to initialize. The function to generate the initial values for each index. The created array. Thrown when count is negative. Array.init 4 (fun v -> v + 5) Evaluates to [| 5; 6; 7; 8 |] Array.init -5 (fun v -> v + 5) Throws ArgumentException Builds a new array whose elements are the corresponding elements of the input array paired with the integer index (from 0) of each element. The input array. The array of indexed elements. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.indexed Evaluates to [| (0, "a"); (1, "b"); (2, "c") |] Applies a key-generating function to each element of an array and yields an array of unique keys. Each unique key contains an array of all elements that match to this key. A function that transforms an element of the array into a comparable key. The input array. The result array. Thrown when the input array is null. let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.groupBy (fun n -> n % 2) Evaluates to [| (1, [| 1; 3; 5 |]); (0, [| 2; 4 |]) |] Returns the first element of the array. The input array. The first element of the array. Thrown when the input array is null. Thrown when the input array is empty. let inputs = [| "banana"; "pear" |] inputs |> Array.head Evaluates to banana [| |] |> Array.head Throws ArgumentException Gets an element from an array. The input array. The input index. Normally the syntax array[index] is preferred. The value of the array at the given index. Thrown when the input array is null. Thrown when the index is negative or the input array does not contain enough elements. let inputs = [| "a"; "b"; "c" |] Array.get inputs 1 Evaluates to "b" let inputs = [| "a"; "b"; "c" |] Array.get inputs 4 Throws IndexOutOfRangeException Apply a function to pairs of elements drawn from the two collections, right-to-left, threading an accumulator argument through the computation. The two input arrays must have the same lengths, otherwise an ArgumentException is raised. The function to update the state given the input elements. The first input array. The second input array. The initial state. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. The final state. Count the positives, negatives and accumulate some text from back to front: type Count = { Positive: int Negative: int Text: string } let inputs1 = [| -1; -2; -3 |] let inputs2 = [| 3; 2; 1 |] let initialState = {Positive = 0; Negative = 0; Text = ""} (inputs1, inputs2, initialState) |||> Array.foldBack2 (fun a b acc -> let text = acc.Text + "(" + string a + "," + string b + ") " if a + b >= 0 then { acc with Positive = acc.Positive + 1 Text = text } else { acc with Negative = acc.Negative + 1 Text = text } ) Evaluates to { Positive = 2 Negative = 1 Text = "(-3,1) (-2,2) (-1,3) " } Applies a function to pairs of elements drawn from the two collections, left-to-right, threading an accumulator argument through the computation. The two input arrays must have the same lengths, otherwise an ArgumentException is raised. The function to update the state given the input elements. The initial state. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. The final state. type CoinToss = Head | Tails let data1 = [| Tails; Head; Tails |] let data2 = [| Tails; Head; Head |] (0, data1, data2) |||> Array.fold2 (fun acc a b -> match (a, b) with | Head, Head -> acc + 1 | Tails, Tails -> acc + 1 | _ -> acc - 1) Evaluates to 1 Applies a function to each element of the array, starting from the end, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f i0 (...(f iN s)) The function to update the state given the input elements. The input array. The initial state. The state object after the folding function is applied to each element of the array. Thrown when the input array is null. type Count = { Positive: int Negative: int Text: string } let sequence = [| 1; 0; -1; -2; 3 |] let initialState = {Positive = 0; Negative = 0; Text = "" } (sequence, initialState) ||> Array.foldBack (fun a acc -> let text = acc.Text + " " + string a if a >= 0 then { acc with Positive = acc.Positive + 1 Text = text } else { acc with Negative = acc.Negative + 1 Text = text }) Evaluates to { Positive = 2 Negative = 3 Text = " 3 -2 -1 0 1" } Applies a function to each element of the collection, threading an accumulator argument through the computation. If the input function is f and the elements are i0...iN then computes f (... (f s i0)...) iN The function to update the state given the input elements. The initial state. The input array. The final state. Thrown when the input array is null. type Charge = | In of int | Out of int let inputs = [| In 1; Out 2; In 3 |] (0, inputs) ||> Array.fold (fun acc charge -> match charge with | In i -> acc + i | Out o -> acc - o) Evaluates to 2 Tests if all corresponding elements of the array satisfy the given predicate pairwise. The predicate is applied to matching elements in the two collections up to the lesser of the two lengths of the collections. If any application returns false then the overall result is false and no further elements are tested. Otherwise, if one collection is longer than the other then the ArgumentException exception is raised. Otherwise, true is returned. The function to test the input elements. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. True if all of the array elements satisfy the predicate. let inputs1 = [| 1; 2; 3 |] let inputs2 = [| 1; 2; 3 |] (inputs1, inputs2) ||> Array.forall2 (=) Evaluates to true. let items1 = [| 2017; 1; 1 |] let items2 = [| 2019; 19; 8 |] (items1, items2) ||> Array.forall2 (=) Evaluates to false. let items1 = [| 1; 2; 3 |] let items2 = [| 1; 2 |] (items1, items2) ||> Array.forall2 (=) Throws ArgumentException. Tests if all elements of the array satisfy the given predicate. The predicate is applied to the elements of the input collection. If any application returns false then the overall result is false and no further elements are tested. Otherwise, true is returned. The function to test the input elements. The input array. True if all of the array elements satisfy the predicate. Thrown when the input array is null. let isEven a = a % 2 = 0 [2; 42] |> Array.forall isEven // evaluates to true [1; 2] |> Array.forall isEven // evaluates to false Returns the index of the last element in the array that satisfies the given predicate. Raise if none of the elements satisfy the predicate. The function to test the input elements. The input array. Thrown if predicate never returns true. Thrown when the input array is null. The index of the last element in the array that satisfies the given predicate. let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.findIndex (fun elm -> elm % 2 = 0) Evaluates to 3 let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.findIndex (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns the index of the first element in the array that satisfies the given predicate. Raise if none of the elements satisfy the predicate. The function to test the input elements. The input array. Thrown if predicate never returns true. Thrown when the input array is null. The index of the first element in the array that satisfies the given predicate. let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.findIndex (fun elm -> elm % 2 = 0) Evaluates to 1 let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.findIndex (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns the last element for which the given function returns 'true'. Raise if no such element exists. The function to test the input elements. The input array. Thrown if predicate never returns true. Thrown when the input array is null. The last element for which predicate returns true. let inputs = [| 2; 3; 4 |] inputs |> Array.findBack (fun elm -> elm % 2 = 0) Evaluates to 4 let inputs = [| 2; 3; 4 |] inputs |> Array.findBack (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns the first element for which the given function returns 'true'. Raise if no such element exists. The function to test the input elements. The input array. Thrown when the input array is null. Thrown if predicate never returns true. The first element for which predicate returns true. let inputs = [| 1; 2; 3 |] inputs |> Array.find (fun elm -> elm % 2 = 0) Evaluates to 2 let inputs = [| 1; 2; 3 |] inputs |> Array.find (fun elm -> elm % 6 = 0) Throws KeyNotFoundException Returns a new collection containing only the elements of the collection for which the given predicate returns "true". The function to test the input elements. The input array. An array containing the elements for which the given predicate returns true. Thrown when the input array is null. let inputs = [| 1; 2; 3; 4 |] inputs |> Array.filter (fun elm -> elm % 2 = 0) Evaluates to [| 2; 4 |] Tests if any pair of corresponding elements of the arrays satisfies the given predicate. The predicate is applied to matching elements in the two collections up to the lesser of the two lengths of the collections. If any application returns true then the overall result is true and no further elements are tested. Otherwise, if one collections is longer than the other then the ArgumentException exception is raised. Otherwise, false is returned. The function to test the input elements. The first input array. The second input array. True if any result from predicate is true. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. let inputs1 = [| 1; 2 |] let inputs2 = [| 1; 2; 0 |] (inputs1, inputs2) ||> Array.exists2 (fun a b -> a > b) Evaluates to false let inputs1 = [| 1; 4 |] let inputs2 = [| 1; 3; 5 |] (inputs1, inputs2) ||> Array.exists2 (fun a b -> a > b) Evaluates to true Tests if any element of the array satisfies the given predicate. The predicate is applied to the elements of the input array. If any application returns true then the overall result is true and no further elements are tested. Otherwise, false is returned. The function to test the input elements. The input array. True if any result from predicate is true. Thrown when the input array is null. let input = [| 1; 2; 3; 4; 5 |] input |> Array.exists (fun elm -> elm % 4 = 0) Evaluates to true let input = [| 1; 2; 3; 4; 5 |] input |> Array.exists (fun elm -> elm % 6 = 0) Evaluates to false Returns a new list with the distinct elements of the input array which do not appear in the itemsToExclude sequence, using generic hash and equality comparisons to compare values. A sequence whose elements that also occur in the input array will cause those elements to be removed from the result. An array whose elements that are not also in itemsToExclude will be returned. An array that contains the distinct elements of array that do not appear in itemsToExclude. Thrown when either itemsToExclude or array is null. let original = [| 1; 2; 3; 4; 5 |] let itemsToExclude = [| 1; 3; 5 |] original |> Array.except itemsToExclude Evaluates to [| 2; 4 |] Returns the only element of the array or None if array is empty or contains more than one element. The input array. The only element of the array or None. Thrown when the input array is null. let inputs = [| "banana" |] inputs |> Array.tryExactlyOne Evaluates to Some banana let inputs = [| "pear"; "banana" |] inputs |> Array.tryExactlyOne Evaluates to None let inputs: int array = [| |] inputs |> Array.tryExactlyOne Evaluates to None Returns the only element of the array. The input array. The only element of the array. Thrown when the input array is null. Thrown when the input does not have precisely one element. let inputs = [| "banana" |] inputs |> Array.exactlyOne Evaluates to banana let inputs = [| "pear"; "banana" |] inputs |> Array.exactlyOne Throws ArgumentException let inputs: int array = [| |] inputs |> Array.exactlyOne Throws ArgumentException Returns an empty array of the given type. The empty array. Array.empty // Evaluates to [| |] Splits the input array into at most count chunks. The maximum number of chunks. The input array. The array split into chunks. Thrown when the input array is null. Thrown when count is not positive. let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.splitInto 3 Evaluates to seq [| [|1; 2|]; [|3; 4|]; [|5|] |] let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.splitInto -1 Throws ArgumentException Returns an array that contains no duplicate entries according to the generic hash and equality comparisons on the keys returned by the given key-generating function. If an element occurs multiple times in the array then the later occurrences are discarded. A function transforming the array items into comparable keys. The input array. The result array. Thrown when the input array is null. let inputs = [| {Bar = 1 };{Bar = 1}; {Bar = 2}; {Bar = 3} |] inputs |> Array.distinctBy (fun foo -> foo.Bar) Evaluates to [| { Bar = 1 }; { Bar = 2 }; { Bar = 3 } |] Returns an array that contains no duplicate entries according to generic hash and equality comparisons on the entries. If an element occurs multiple times in the array then the later occurrences are discarded. The input array. The result array. Thrown when the input array is null. let input = [| 1; 1; 2; 3 |] input |> Array.distinct Evaluates to [| 1; 2; 3 |] Divides the input array into chunks of size at most chunkSize. The maximum size of each chunk. The input array. The array divided into chunks. Thrown when the input array is null. Thrown when chunkSize is not positive. let input = [| 1; 2; 3 |] input |> Array.chunkBySize 2 Evaluates to [| [|1; 2|]; [|3|] |] let input = [| 1; 2; 3 |] input |> Array.chunkBySize -2 Throws ArgumentException Applies the given function to each element of the array. Returns the array comprised of the results x for each element where the function returns Some(x) The function to generate options from the elements. The input array. The array of results. Thrown when the input array is null. let input = [| Some 1; None; Some 2 |] input |> Array.choose id Evaluates to [| 1; 2 |] let input = [| 1; 2; 3 |] input |> Array.choose (fun n -> if n % 2 = 0 then Some n else None) Evaluates to [| 2 |] Applies the given function to successive elements, returning the first result where the function returns Some(x) for some x. If the function never returns Some(x) then is raised. The function to generate options from the elements. The input array. Thrown when the input array is null. Thrown if every result from chooser is None. The first result. let input = [| 1; 2; 3 |] input |> Array.pick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to "2". let input = [| 1; 2; 3 |] input |> Array.pick (fun n -> if n > 3 = 0 then Some (string n) else None) Throws KeyNotFoundException. Fills a range of elements of the array with the given value. The target array. The index of the first element to set. The number of elements to set. The value to set. Thrown when the input array is null. Thrown when either targetIndex or count is negative. let target = [| 0; 1; 2; 3; 4; 5 |] Array.fill target 3 2 100 After evaluation target contains [| 0; 1; 2; 100; 100; 5 |]. Applies the given function to successive elements, returning the first result where the function returns Some(x) for some x. If the function never returns Some(x) then None is returned. The function to transform the array elements into options. The input array. The first transformed element that is Some(x). Thrown when the input array is null. let input = [| 1; 2; 3 |] input |> Array.tryPick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to Some "2". let input = [| 1; 2; 3 |] input |> Array.tryPick (fun n -> if n > 3 = 0 then Some (string n) else None) Evaluates to None. Returns the first element of the array, or None if the array is empty. The input array. Thrown when the input array is null. The first element of the array or None. let inputs = [| "banana"; "pear" |] inputs |> Array.tryHead Evaluates to Some "banana" let inputs : int array = [| |] inputs |> Array.tryHead Evaluates to None Creates an array whose elements are all initially the given value. The length of the array to create. The value for the elements. The created array. Thrown when count is negative. Array.create 4 "a" Evaluates to a new array containing[| "a"; "a"; "a"; "a" |]. let cell = ref "a" let array = Array.create 2 cell cell.Value <- "b" Before evaluation of the last line, array contains[| { contents = "a"}; { contents = "a"} |]. After evaluation of the last line array contains[| { contents = "b"}; { contents = "b"} |]. Note each entry in the array is the same mutable cell object. Applies a key-generating function to each element of an array and returns an array yielding unique keys and their number of occurrences in the original array. A function transforming each item of the input array into a key to be compared against the others. The input array. The result array. Thrown when the input array is null. type Foo = { Bar: string } let inputs = [| {Bar = "a"}; {Bar = "b"}; {Bar = "a"} |] inputs |> Array.countBy (fun foo -> foo.Bar) Evaluates to [| ("a", 2); ("b", 1) |] Builds a new array that contains the elements of the given array. The input array. A copy of the input array. Thrown when the input array is null. let source = [| 12; 13; 14 |] Array.copy source Evaluates to a new array containing[| 12; 13; 14 |]. Tests if the array contains the specified element. The value to locate in the input array. The input array. True if the input array contains the specified element; false otherwise. Thrown when the input array is null. [| 1; 2 |] |> Array.contains 2 // evaluates to true [| 1; 2 |] |> Array.contains 5 // evaluates to false Builds a new array that contains the elements of each of the given sequence of arrays. The input sequence of arrays. The concatenation of the sequence of input arrays. Thrown when the input sequence is null. let inputs = [ [| 1; 2 |]; [| 3 |]; [| 4; 5 |] ] inputs |> Array.concat Evaluates to [| 1; 2; 3; 4; 5 |] Compares two arrays using the given comparison function, element by element. A function that takes an element from each array and returns an int. If it evaluates to a non-zero value iteration is stopped and that value is returned. The first input array. The second input array. Returns the first non-zero result from the comparison function. If the first array has a larger element, the return value is always positive. If the second array has a larger element, the return value is always negative. When the elements are equal in the two arrays, 1 is returned if the first array is longer, 0 is returned if they are equal in length, and -1 is returned when the second array is longer. Thrown when either of the input arrays is null. let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [| 1; 10 |] let input2 = [| 1; 10 |] (input1, input2) ||> Array.compareWith closerToNextDozen Evaluates to 0 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [| 1; 5 |] let input2 = [| 1; 8 |] (input1, input2) ||> Array.compareWith closerToNextDozen Evaluates to -1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [| 1; 11 |] let input2 = [| 1; 13 |] (input1, input2) ||> Array.compareWith closerToNextDozen Evaluates to 1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [| 1; 2 |] let input2 = [| 1 |] (input1, input2) ||> Array.compareWith closerToNextDozen Evaluates to 1 let closerToNextDozen a b = (a % 12).CompareTo(b % 12) let input1 = [| 1 |] let input2 = [| 1; 2 |] (input1, input2) ||> Array.compareWith closerToNextDozen Evaluates to -1 For each element of the array, applies the given function. Concatenates all the results and return the combined array. The function to create sub-arrays from the input array elements. The input array. The concatenation of the sub-arrays. Thrown when the input array is null. type Foo = { Bar: int array } let input = [| {Bar = [| 1; 2 |]}; {Bar = [| 3; 4 |]} |] input |> Array.collect (fun foo -> foo.Bar) Evaluates to [| 1; 2; 3; 4 |] let input = [[1; 2]; [3; 4]] input |> Array.collect id Evaluates to [| 1; 2; 3; 4 |] Reads a range of elements from the first array and write them into the second. The source array. The starting index of the source array. The target array. The starting index of the target array. The number of elements to copy. Slicing syntax is generally preferred, e.g. let source = [| 12; 13; 14 |] let target = [| 0; 1; 2; 3; 4; 5 |] target[3..4] <- source[1..2] Thrown when either of the input arrays is null. Thrown when any of sourceIndex, targetIndex or count are negative, or when there aren't enough elements in source or target. let source = [| 12; 13; 14 |] let target = [| 0; 1; 2; 3; 4; 5 |] Array.blit source 1 target 3 2 After evaluation target contains [| 0; 1; 2; 13; 14; 5 |]. Returns the average of the elements generated by applying the function to each element of the array. The function to transform the array elements before averaging. The input array. Thrown when array is empty. The computed average. Thrown when the input array is null. type Foo = { Bar: float } let input = [| {Bar = 2.0}; {Bar = 4.0} |] input |> Array.averageBy (fun foo -> foo.Bar) Evaluates to 3.0 type Foo = { Bar: float } let input : Foo array = [| |] input |> Array.averageBy (fun foo -> foo.Bar) Throws ArgumentException Returns the average of the elements in the array. The input array. Thrown when array is empty. Thrown when the input array is null. The average of the elements in the array. [| 1.0; 2.0; 6.0 |] |> Array.average Evaluates to 3.0 [| |] |> Array.average Throws ArgumentException Builds a new array that contains the elements of the first array followed by the elements of the second array. The first input array. The second input array. The resulting array. Thrown when either of the input arrays is null. Array.append [| 1; 2 |] [| 3; 4 |] Evaluates to [| 1; 2; 3; 4 |]. Returns a new array that contains all pairings of elements from the first and second arrays. The first input array. The second input array. Thrown when either of the input arrays is null. The resulting array of pairs. ([| 1; 2 |], [| 3; 4 |]) ||> Array.allPairs Evaluates to [| (1, 3); (1, 4); (2, 3); (2, 4) |] Returns a new collection containing only the elements of the collection for which the given predicate returns true. The function to test the input elements. The input array. An array containing the elements for which the given predicate returns true. Thrown when the input array is null. let inputs = [| 1; 2; 3; 4 |] inputs |> Array.Parallel.filter (fun elm -> elm % 2 = 0) Evaluates to [| 2; 4 |] Combines the two arrays into an array of pairs. The two arrays must have equal lengths, otherwise an ArgumentException is raised. The first input array. The second input array. Thrown when either of the input arrays is null. Thrown when the input arrays differ in length. The array of tupled elements. let numbers = [|1; 2|] let names = [|"one"; "two"|] Array.Parallel.zip numbers names Evaluates to [| (1, "one"); (2, "two") |]. Sorts the elements of an array in parallel, in descending order, using the given projection for the keys and returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to transform array elements into the type that is compared. The input array. The sorted array. let input = [| "a"; "bbb"; "cccc"; "dd" |] input |> Array.Parallel.sortByDescending (fun s -> s.Length) Evaluates to [|"cccc"; "bbb"; "dd"; "a"|]. Sorts the elements of an array in parallel, in descending order, returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The input array. The sorted array. let input = [| 8; 4; 3; 1; 6; 1 |] input |> Array.Parallel.sortDescending Evaluates to [| 8; 6; 4; 3; 1; 1 |]. Sorts the elements of an array by mutating the array in-place in parallel, using the given comparison function. Elements are compared using . The input array. Thrown when the input array is null. let array = [| 8; 4; 3; 1; 6; 1 |] Array.sortInPlace array After evaluation array contains [| 1; 1; 3; 4; 6; 8 |]. Sorts the elements of an array by mutating the array in-place in parallel, using the given comparison function as the order. The function to compare pairs of array elements. The input array. Thrown when the input array is null. The following sorts entries using a comparison function that compares string lengths then index numbers: let compareEntries (n1: int, s1: string) (n2: int, s2: string) = let c = compare s1.Length s2.Length if c <> 0 then c else compare n1 n2 let array = [| (0,"aa"); (1,"bbb"); (2,"cc"); (3,"dd") |] array |> Array.Parallel.sortInPlaceWith compareEntries After evaluation array contains [|(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")|]. Sorts the elements of an array by mutating the array in-place in parallel, using the given projection for the keys. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to transform array elements into the type that is compared. The input array. Thrown when the input array is null. let array = [| "a"; "bbb"; "cccc"; "dd" |] array |> Array.Parallel.sortInPlaceBy (fun s -> s.Length) After evaluation array contains [|"a"; "dd"; "bbb"; "cccc"|]. Sorts the elements of an array in parallel, using the given comparison function as the order, returning a new array. This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to compare pairs of array elements. The input array. The sorted array. Thrown when the input array is null. Sort an array of pairs using a comparison function that compares string lengths then index numbers: let compareEntries (n1: int, s1: string) (n2: int, s2: string) = let c = compare s1.Length s2.Length if c <> 0 then c else compare n1 n2 let input = [| (0,"aa"); (1,"bbb"); (2,"cc"); (3,"dd") |] input |> Array.Parallel.sortWith compareEntries Evaluates to [|(0, "aa"); (2, "cc"); (3, "dd"); (1, "bbb")|]. Sorts the elements of an array in parallel, using the given projection for the keys and returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The function to transform array elements into the type that is compared. The input array. The sorted array. Thrown when the input array is null. let input = [| "a"; "bbb"; "cccc"; "dd" |] input |> Array.Parallel.sortBy (fun s -> s.Length) Evaluates to [|"a"; "dd"; "bbb"; "cccc"|]. Sorts the elements of an array in parallel, returning a new array. Elements are compared using . This is not a stable sort, i.e. the original order of equal elements is not necessarily preserved. For a stable sort, consider using . The input array. The sorted array. Thrown when the input array is null. let input = [| 8; 4; 3; 1; 6; 1 |] Array.Parallel.sort input Evaluates to [| 1; 1 3; 4; 6; 8 |]. Split the collection into two collections, containing the elements for which the given predicate returns "true" and "false" respectively Performs the operation in parallel using . The order in which the given function is applied to indices is not specified. The function to test the input elements. The input array. The two arrays of results. Thrown when the input array is null. let inputs = [| 1; 2; 3; 4 |] inputs |> Array.Parallel.partition (fun x -> x % 2 = 0) Evaluates to ([|2; 4|], [|1; 3|]). Create an array given the dimension and a generator function to compute the elements. Performs the operation in parallel using . The order in which the given function is applied to indices is not specified. The array of results. Array.Parallel.init 4 (fun v -> v + 5) Evaluates to [| 5; 6; 7; 8 |] Apply the given function to each element of the array. The integer passed to the function indicates the index of element. Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The input array. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.Parallel.iteri (fun i v -> printfn "{i}: {v}") Evaluates to unit and prints the following to the console in an unspecified order: 0: a 2: c 1: b Apply the given function to each element of the array. Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The input array. Thrown when the input array is null. let inputs = [| "a"; "b"; "c" |] inputs |> Array.Parallel.iter (printfn "%s") Evaluates to unit and prints the following to the console in an unspecified order: a c b Applies a key-generating function to each element of an array in parallel and yields an array of unique keys. Each unique key contains an array of all elements that match to this key. Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The order of the keys and values in the result is also not specified A function that transforms an element of the array into a comparable key. The input array. The result array. Thrown when the input array is null. let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.Parallel.groupBy (fun n -> n % 2) Evaluates to [| (1, [| 1; 3; 5 |]); (0, [| 2; 4 |]) |] Build a new array whose elements are the results of applying the given function to each of the elements of the array. The integer index passed to the function indicates the index of element being transformed. Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The input array. The array of results. Thrown when the input array is null. let inputs = [| 10; 10; 10 |] inputs |> Array.Parallel.mapi (fun i x -> i + x) Evaluates to [| 10; 11; 12 |] Build a new array whose elements are the results of applying the given function to each of the elements of the array. Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The input array. The array of results. Thrown when the input array is null. let inputs = [| "a"; "bbb"; "cc" |] inputs |> Array.Parallel.map (fun x -> x.Length) Evaluates to [| 1; 3; 2 |] For each element of the array, apply the given function. Concatenate all the results and return the combined array. Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The input array. 'U array Thrown when the input array is null. type Foo = { Bar: int array } let input = [| {Bar = [| 1; 2 |]}; {Bar = [| 3; 4 |]} |] input |> Array.Parallel.collect (fun foo -> foo.Bar) Evaluates to [| 1; 2; 3; 4 |] let input = [| [| 1; 2 |]; [| 3; 4 |] |] input |> Array.Parallel.collect id Evaluates to [| 1; 2; 3; 4 |] Apply the given function to each element of the array. Return the array comprised of the results x for each element where the function returns Some(x). Performs the operation in parallel using . The order in which the given function is applied to elements of the input array is not specified. The function to generate options from the elements. The input array. The array of results. Thrown when the input array is null. let input = [| Some 1; None; Some 2 |] input |> Array.Parallel.choose id Evaluates to [| 1; 2 |] let input = [| 1; 2; 3 |] input |> Array.Parallel.choose (fun n -> if n % 2 = 0 then Some n else None) Evaluates to [| 2 |] Returns the average of the elements generated by applying the function to each element of the array. The function to transform the array elements before averaging. The input array. Thrown when array is empty. The computed average. Thrown when the input array is null. type Foo = { Bar: float } let input = [| {Bar = 2.0}; {Bar = 4.0} |] input |> Array.Parallel.averageBy (fun foo -> foo.Bar) Evaluates to 3.0 type Foo = { Bar: float } let input : Foo array = [| |] input |> Array.Parallel.averageBy (fun foo -> foo.Bar) Throws ArgumentException Returns the average of the elements in the array. The input array. Thrown when array is empty. Thrown when the input array is null. The average of the elements in the array. [| 1.0; 2.0; 6.0 |] |> Array.Parallel.average Evaluates to 3.0 [| |] |> Array.Parallel.average Throws ArgumentException Returns the sum of the results generated by applying the function to each element of the array. The function to transform the array elements into the type to be summed. The input array. The resulting sum. Thrown when the input array is null. let input = [| "aa"; "bbb"; "cc" |] input |> Array.Parallel.sumBy (fun s -> s.Length) Evaluates to 7. Returns the sum of the elements in the array. The input array. The resulting sum. Thrown when the input array is null. let input = [| 1; 5; 3; 2 |] input |> Array.Parallel.sum Evaluates to 11. Returns the lowest of all elements of the array, compared via Operators.min on the function result. Throws ArgumentException for empty arrays. The function to transform the elements into a type supporting comparison. The input array. Thrown when the input array is null. Thrown when the input array is empty. The minimum element. let inputs = [| "aaa"; "b"; "cccc" |] inputs |> Array.Parallel.minBy (fun s -> s.Length) Evaluates to "b" let inputs: string array= [| |] inputs |> Array.Parallel.minBy (fun s -> s.Length) Throws System.ArgumentException. Returns the smallest of all elements of the array, compared via Operators.min. Throws ArgumentException for empty arrays The input array. Thrown when the input array is null. Thrown when the input array is empty. The minimum element. let inputs = [| 10; 12; 11 |] inputs |> Array.Parallel.min Evaluates to 10 let inputs: int array= [| |] inputs |> Array.Parallel.min Throws System.ArgumentException. Returns the greatest of all elements of the array, compared via Operators.max on the function result. Throws ArgumentException for empty arrays. The function to transform the elements into a type supporting comparison. The input array. Thrown when the input array is null. Thrown when the input array is empty. The maximum element. let inputs = [| "aaa"; "b"; "cccc" |] inputs |> Array.Parallel.maxBy (fun s -> s.Length) Evaluates to "cccc" let inputs: string array= [| |] inputs |> Array.Parallel.maxBy (fun s -> s.Length) Throws System.ArgumentException. Returns the greatest of all elements of the array, compared via Operators.max. Throws ArgumentException for empty arrays. The input array. Thrown when the input array is null. Thrown when the input array is empty. The maximum element. let inputs = [| 10; 12; 11 |] inputs |> Array.Parallel.max Evaluates to 12 let inputs: int array= [| |] inputs |> Array.Parallel.max Throws System.ArgumentException. Applies a projection function to each element of the array in parallel, reducing elements in each thread with a dedicated 'reduction' function. After processing entire input, results from all threads are reduced together. Raises ArgumentException if the array is empty. The order of processing is not guaranteed. For that reason, the 'reduction' function argument should be commutative. (That is, changing the order of execution must not affect the result) The function to project from elements of the input array The function to reduce a pair of projected elements to a single element. The input array. Thrown when the input array is null. Thrown when the input array is empty. The final result of the reductions. let inputs = [| "1"; "3"; "4"; "2" |] inputs |> Array.Parallel.reduceBy (fun x -> int x) (+) Evaluates to 1 + 3 + 4 + 2. However, the system could have decided to compute (1+3) and (4+2) first, and then put them together. Applies a function to each element of the array in parallel, threading an accumulator argument through the computation for each thread involved in the computation. After processing entire input, results from all threads are reduced together. Raises ArgumentException if the array is empty. The order of processing is not guaranteed. For that reason, the 'reduce' function argument should be commutative. (That is, changing the order of execution must not affect the result) Also, compared to the non-parallel version of Array.reduce, the 'reduce' function may be invoked more times due to the resulting reduction from participating threads. The function to reduce a pair of elements to a single element. The input array. Thrown when the input array is null. Thrown when the input array is empty. Result of the reductions. let inputs = [| 1; 3; 4; 2 |] inputs |> Array.Parallel.reduce (fun a b -> a + b) Evaluates to 1 + 3 + 4 + 2. However, the system could have decided to compute (1+3) and (4+2) first, and then put them together. Applies the given function to successive elements, returning the first result where the function returns Some(x) for some x. If the function never returns Some(x) then None is returned. The function to transform the array elements into options. The input array. The first transformed element that is Some(x). Thrown when the input array is null. let input = [| 1; 2; 3 |] input |> Array.Parallel.tryPick (fun n -> if n % 2 = 0 then Some (string n) else None) Evaluates to Some 2. let input = [| 1; 2; 3 |] input |> Array.Parallel.tryPick (fun n -> if n > 3 = 0 then Some (string n) else None) Evaluates to None. Returns the index of the first element in the array that satisfies the given predicate. Returns None if no such element exists. The function to test the input elements. The input array. Thrown when the input array is null. The index of the first element that satisfies the predicate, or None. Try to find the index of the first even number: let inputs = [| 1; 2; 3; 4; 5 |] inputs |> Array.Parallel.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to Some 1 Try to find the index of the first even number: let inputs = [| 1; 3; 5; 7 |] inputs |> Array.Parallel.tryFindIndex (fun elm -> elm % 2 = 0) Evaluates to None Returns the first element for which the given function returns True. Returns None if no such element exists. The function to test the input elements. The input array. The first element that satisfies the predicate, or None. Thrown when the input array is null. Try to find the first even number: let inputs = [| 1; 2; 3 |] inputs |> Array.Parallel.tryFind (fun elm -> elm % 2 = 0) Evaluates to Some 2. Try to find the first even number: let inputs = [| 1; 5; 3 |] inputs |> Array.Parallel.tryFind (fun elm -> elm % 2 = 0) Evaluates to None Tests if any element of the array satisfies the given predicate. The predicate is applied to the elements of the input array in parallel. If any application returns true then the overall result is true and testing of other elements in all threads is stopped at system's earliest convenience. Otherwise, false is returned. The function to test the input elements. The input array. True if any result from predicate is true. Thrown when the input array is null. let input = [| 1; 2; 3; 4; 5 |] input |> Array.Parallel.exists (fun elm -> elm % 4 = 0) Evaluates to true let input = [| 1; 2; 3; 4; 5 |] input |> Array.Parallel.exists (fun elm -> elm % 6 = 0) Evaluates to false Tests if all elements of the array satisfy the given predicate. The predicate is applied to the elements of the input collection in parallel. If any application returns false then the overall result is false and testing of other elements in all threads is stopped at system's earliest convenience. Otherwise, true is returned. The function to test the input elements. The input array. True if all of the array elements satisfy the predicate. Thrown when the input array is null. let isEven a = a % 2 = 0 [2; 42] |> Array.Parallel.forall isEven // evaluates to true [1; 2] |> Array.Parallel.forall isEven // evaluates to false Provides parallel operations on arrays Contains operations for working with arrays. See also F# Language Guide - Arrays. Sets the value of an element in an array. You can also use the syntax 'array.[index1,index2,index3,index4] <- value'. The input array. The index along the first dimension. The index along the second dimension. The index along the third dimension. The index along the fourth dimension. The value to set. Indexer syntax is generally preferred, e.g. let array: float[,,,] = Array4D.zeroCreate 2 3 4 5 array[0,2,1,3] <- 5.0 let array = Array4D.zeroCreate 2 3 4 5 Array4D.2et array 0 2 1 3 5.0 Fetches an element from a 4D array. You can also use the syntax 'array.[index1,index2,index3,index4]' The input array. The index along the first dimension. The index along the second dimension. The index along the third dimension. The index along the fourth dimension. The value at the given index. Indexer syntax is generally preferred, e.g. let array: float[,,,] = Array4D.zeroCreate 2 3 4 5 array[0,2,1,3] let array = Array4D.zeroCreate 2 3 4 5 Array4D.get array 0 2 1 3 Creates an array where the entries are initially the "default" value. The length of the first dimension. The length of the second dimension. The length of the third dimension. The length of the fourth dimension. The created array. let array : float[,,,] = Array4D.zeroCreate 2 3 3 5 After evaluation array is a 2x3x3x5 array with contents all zero. Returns the length of an array in the fourth dimension. The input array. The length of the array in the fourth dimension. let array = Array4D.init 2 3 4 5 (fun i j k -> 100*i + 10*j + k) array |> Array4D.length4 Evaluates to 5. Returns the length of an array in the third dimension. The input array. The length of the array in the third dimension. let array = Array4D.init 2 3 4 5 (fun i j k -> 100*i + 10*j + k) array |> Array4D.length3 Evaluates to 4. Returns the length of an array in the second dimension. The input array. The length of the array in the second dimension. let array = Array4D.init 2 3 4 5 (fun i j k -> 100*i + 10*j + k) array |> Array4D.length2 Evaluates to 3. Returns the length of an array in the first dimension The input array. The length of the array in the first dimension. let array = Array4D.init 2 3 4 5 (fun i j k -> 100*i + 10*j + k) array |> Array4D.length1 Evaluates to 2. Creates an array given the dimensions and a generator function to compute the elements. The length of the first dimension. The length of the second dimension. The length of the third dimension. The length of the fourth dimension. The function to create an initial value at each index in the array. The created array. Array4D.init 2 2 2 2 (fun i j k l -> i*1000+j*100+k*10+l) Evaluates to a 2x2x2x2 array with contents [[[[0; 1]; [10; 11]]; [[100; 101]; [110; 111]]];[[[1000; 1]; [1010; 1011]]; [[1100; 1101]; [1110; 1111]]]] Creates an array whose elements are all initially the given value The length of the first dimension. The length of the second dimension. The length of the third dimension. The length of the fourth dimension. The initial value for each element of the array. The created array. Array4D.create 2 2 2 2 1 Evaluates to a 2x2x2x2 array with all entries 1 Contains operations for working with rank 4 arrays. Creates an array where the entries are initially the "default" value. The length of the first dimension. The length of the second dimension. The length of the third dimension. The created array. let array : float[,,] = Array3D.zeroCreate 2 3 3 After evaluation array is a 2x3x3 array with contents all zero. Sets the value of an element in an array. You can also use the syntax 'array.[index1,index2,index3] <- value'. The input array. The index along the first dimension. The index along the second dimension. The index along the third dimension. The value to set at the given index. Indexer syntax is generally preferred, e.g. let array = Array3D.zeroCreate 2 3 3 array[0,2,1] < 4.0 Evaluates to 11. let array = Array3D.zeroCreate 2 3 3 Array3D.set array 0 2 1 4.0 After evaluation array is a 2x3x3 array with contents [[[0.0; 0.0; 0.0]; [0.0; 4.0; 0.0]]; [[0.0; 0.0; 0.0]; [0.0; 0.0; 0.0]]] Builds a new array whose elements are the results of applying the given function to each of the elements of the array. The integer indices passed to the function indicates the element being transformed. For non-zero-based arrays the basing on an input array will be propagated to the output array. The function to transform the elements at each index in the array. The input array. The array created from the transformed elements. let inputs = Array3D.zeroCreate 2 3 3 inputs |> Array3D.mapi (fun i j k v -> 100*i + 10*j + k) Evaluates to a 2x3x3 array with contents [[[0; 2; 4]; [20; 22; 24]]; [[200; 202; 204]; [220; 222; 224]]] Builds a new array whose elements are the results of applying the given function to each of the elements of the array. For non-zero-based arrays the basing on an input array will be propagated to the output array. The function to transform each element of the array. The input array. The array created from the transformed elements. let inputs = Array3D.init 2 3 3 (fun i j k -> 100*i + 10*j + k) inputs |> Array3D.map (fun v -> 2 * v) Evaluates to a 2x3x3 array with contents [[[0; 2; 4]; [20; 22; 24]]; [[200; 202; 204]; [220; 222; 224]]] Returns the length of an array in the third dimension. The input array. The length of the array in the third dimension. let array = Array3D.init 2 3 4 (fun i j k -> 100*i + 10*j + k) array |> Array3D.length3 Evaluates to 4. Returns the length of an array in the second dimension. The input array. The length of the array in the second dimension. let array = Array3D.init 2 3 4 (fun i j k -> 100*i + 10*j + k) array |> Array3D.length2 Evaluates to 3. Returns the length of an array in the first dimension The input array. The length of the array in the first dimension. let array = Array3D.init 2 3 4 (fun i j k -> 100*i + 10*j + k) array |> Array3D.length1 Evaluates to 2. Applies the given function to each element of the array. The integer indices passed to the function indicates the index of element. The function to apply to each element of the array. The input array. let inputs = Array3D.init 2 2 3 (fun i j k -> 100*i + 10*j + k) inputs |> Array3D.iteri (fun i j k v -> printfn $"value at ({i},{j},{k}) = {v}") Evaluates to unit and prints value at (0,0,0) = 0 value at (0,0,1) = 1 value at (0,0,2) = 2 value at (0,1,0) = 10 value at (0,1,1) = 11 value at (0,1,2) = 12 value at (1,0,0) = 100 value at (1,0,1) = 101 value at (1,0,2) = 102 value at (1,1,0) = 110 value at (1,1,1) = 111 value at (1,1,2) = 112 in the console. Applies the given function to each element of the array. The function to apply to each element of the array. The input array. let inputs = Array3D.init 2 2 3 (fun i j k -> 100*i + 10*j + k) inputs |> Array3D.iter (fun v -> printfn $"value = {v}") Evaluates to unit and prints value = 0 value = 1 value = 2 value = 10 value = 11 value = 12 value = 100 value = 101 value = 102 value = 110 value = 111 value = 112 in the console. Fetches an element from a 3D array. You can also use the syntax 'array.[index1,index2,index3]' The input array. The index along the first dimension. The index along the second dimension. The index along the third dimension. The value at the given index. Indexer syntax is generally preferred, e.g. let array = Array3D.init 2 3 3 (fun i j k -> 100*i + 10*j + k) array[0,2,1] Evaluates to 11. let array = Array3D.init 2 3 3 (fun i j k -> 100*i + 10*j + k) Array3D.get array 0 2 1 Evaluates to 21. Creates an array given the dimensions and a generator function to compute the elements. The length of the first dimension. The length of the second dimension. The length of the third dimension. The function to create an initial value at each index into the array. The created array. Array3D.init 2 2 3 (fun i j k -> 100*i + 10*j + k) Evaluates to a 2x2x3 array with contents [[[0; 1; 2]; [10; 11; 12]]; [[100; 101; 102]; [110; 111; 112]]] Creates an array whose elements are all initially the given value. The length of the first dimension. The length of the second dimension. The length of the third dimension. The value of the array elements. The created array. Array3D.create 2 2 3 1 Evaluates to a 2x3 array with contents [[[1; 1; 1]; [1; 1; 1]]; [[1; 1; 1]; [1; 1; 1]]] Contains operations for working with rank 3 arrays. See also F# Language Guide - Arrays. Returns binding for the largest key in the map. Raise KeyNotFoundException when map is empty. The input map. Thrown if the map is empty. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.maxKeyValue // evaluates to (2, "b") Returns binding for the smallest key in the map. Raise KeyNotFoundException when map is empty. The input map. Thrown if the map is empty. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.minKeyValue // evaluates to (1, "a") The values in the map, including the duplicates. The sequence will be ordered by the keys of the map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.values // evaluates to seq ["a"; "b"] The keys in the map. The sequence will be ordered by the keys of the map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.keys // evaluates to seq [1; 2] The number of bindings in the map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.count // evaluates to 2 Returns the key of the first mapping in the collection that satisfies the given predicate. Returns 'None' if no such element exists. The function to test the input elements. The input map. The first key for which the predicate returns true or None if the predicate evaluates to false for each key/value pair. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.tryFindKey (fun n s -> n = s.Length) // evaluates to Some 1 sample |> Map.tryFindKey (fun n s -> n < s.Length) // evaluates to None Evaluates the function on each mapping in the collection. Returns the key for the first mapping where the function returns 'true'. Raise KeyNotFoundException if no such element exists. The function to test the input elements. The input map. Thrown if the key does not exist in the map. The first key for which the predicate evaluates true. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.findKey (fun n s -> n = s.Length) // evaluates to 1 sample |> Map.findKey (fun n s -> n < s.Length) // throws KeyNotFoundException Lookup an element in the map, returning a Some value if the element is in the domain of the map and None if not. The input key. The input map. The found Some value or None. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.tryFind 1 // evaluates to Some "a" sample |> Map.tryFind 3 // evaluates to None Removes an element from the domain of the map. No exception is raised if the element is not present. The input key. The input map. The resulting map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.remove 1 // evaluates to map [(2, "b")] sample |> Map.remove 3 // equal to sample Builds two new maps, one containing the bindings for which the given predicate returns 'true', and the other the remaining bindings. The function to test the input elements. The input map. A pair of maps in which the first contains the elements for which the predicate returned true and the second containing the elements for which the predicated returned false. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.partition (fun n s -> n = s.Length) // evaluates to (map [(1, "a")], map [(2, "b")]) Tests if an element is in the domain of the map. The input key. The input map. True if the map contains the key. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.containsKey 1 // evaluates to true sample |> Map.containsKey 3 // evaluates to false Builds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The key passed to the function indicates the key of element being transformed. The function to transform the key/value pairs. The input map. The resulting map of keys and transformed values. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.map (fun n s -> sprintf "%i %s" n s) // evaluates to map [(1, "1 a"); (2, "2 b")] Returns true if the given predicate returns true for all of the bindings in the map. The function to test the input elements. The input map. True if the predicate evaluates to true for all of the bindings in the map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.forall (fun n s -> n >= s.Length) // evaluates to true sample |> Map.forall (fun n s -> n = s.Length) // evaluates to false Builds a new map containing only the bindings for which the given predicate returns 'true'. The function to test the key/value pairs. The input map. The filtered map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.filter (fun n s -> n = s.Length) // evaluates to map [(1, "a")] Returns true if the given predicate returns true for one of the bindings in the map. The function to test the input elements. The input map. True if the predicate returns true for one of the key/value pairs. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.exists (fun n s -> n = s.Length) // evaluates to true sample |> Map.exists (fun n s -> n < s.Length) // evaluates to false Applies the given function to each binding in the dictionary The function to apply to each key/value pair. The input map. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.iter (fun n s -> printf "%i %s " n s) Prints "1 a 2 b ". Folds over the bindings in the map The function to update the state given the input key/value pairs. The initial state. The input map. The final state value. let sample = Map [ (1, "a"); (2, "b") ] ("initial", sample) ||> Map.fold (fun state n s -> sprintf "%s %i %s" state n s) Evaluates to "initial 1 a 2 b". Folds over the bindings in the map. The function to update the state given the input key/value pairs. The input map. The initial state. The final state value. let sample = Map [ (1, "a"); (2, "b") ] (sample, "initial") ||> Map.foldBack (fun n s state -> sprintf "%i %s %s" n s state) Evaluates to "1 a 2 b initial" Searches the map looking for the first element where the given function returns a Some value. Raise KeyNotFoundException if no such element exists. The function to generate options from the key/value pairs. The input map. Thrown if no element returns a Some value when evaluated by the chooser function The first result. let sample = Map [ (1, "a"); (2, "b"); (10, "ccc"); (20, "ddd") ] sample |> Map.pick (fun n s -> if n > 5 && s.Length > 2 then Some s else None) Evaluates to "ccc" let sample = Map [ (1, "a"); (2, "b"); (10, "ccc"); (20, "ddd") ] sample |> Map.pick (fun n s -> if n > 5 && s.Length > 4 then Some s else None) Raises KeyNotFoundException Searches the map looking for the first element where the given function returns a Some value. The function to generate options from the key/value pairs. The input map. The first result. let sample = Map [ (1, "a"); (2, "b"); (10, "ccc"); (20, "ddd") ] sample |> Map.tryPick (fun n s -> if n > 5 && s.Length > 2 then Some s else None) Evaluates to Some "ccc". let sample = Map [ (1, "a"); (2, "b"); (10, "ccc"); (20, "ddd") ] sample |> Map.tryPick (fun n s -> if n > 5 && s.Length > 4 then Some s else None) Evaluates to None. Lookup an element in the map, raising KeyNotFoundException if no binding exists in the map. The input key. The input map. Thrown when the key does not exist in the map. The value mapped to the given key. let sample = Map [ (1, "a"); (2, "b") ] sample |> Map.find 1 // evaluates to "a" sample |> Map.find 3 // throws KeyNotFoundException The empty map. let emptyMap = Map.empty<int, string> Is the map empty? The input map. True if the map is empty. let emptyMap = Map.empty<int, string> emptyMap |> Map.isEmpty // evaluates to true let notEmptyMap = Map [ (1, "a"); (2, "b") ] emptyMap |> Map.isEmpty // evaluates to false Returns an array of all key-value pairs in the mapping. The array will be ordered by the keys of the map. The input map. The array of key/value pairs. let input = Map [ (1, "a"); (2, "b") ] input |> Map.toArray // evaluates to [|(1, "a"); (2, "b")|] Returns a list of all key-value pairs in the mapping. The list will be ordered by the keys of the map. The input map. The list of key/value pairs. let input = Map [ (1, "a"); (2, "b") ] input |> Map.toList // evaluates to [(1, "a"); (2, "b")] Views the collection as an enumerable sequence of pairs. The sequence will be ordered by the keys of the map. The input map. The sequence of key/value pairs. let input = Map [ (1, "a"); (2, "b") ] input |> Map.toSeq // evaluates to seq [(1, "a"); (2, "b")] Returns a new map made from the given bindings. The input sequence of key/value pairs. The resulting map. let input = seq { (1, "a"); (2, "b") } input |> Map.ofSeq // evaluates to map [(1, "a"); (2, "b")] Returns a new map made from the given bindings. The input array of key/value pairs. The resulting map. let input = [| (1, "a"); (2, "b") |] input |> Map.ofArray // evaluates to map [(1, "a"); (2, "b")] Returns a new map made from the given bindings. The input list of key/value pairs. The resulting map. let input = [ (1, "a"); (2, "b") ] input |> Map.ofList // evaluates to map [(1, "a"); (2, "b")] Returns a new map with the value stored under key changed according to f. The input key. The change function. The input map. The resulting map. let input = Map [ (1, "a"); (2, "b") ] input |> Map.change 1 (fun x -> match x with | Some s -> Some (s + "z") | None -> None ) // evaluates to map [(1, "az"); (2, "b")] Returns a new map with the binding added to the given map. If a binding with the given key already exists in the input map, the existing binding is replaced by the new binding in the result map. The input key. The input value. The input map. The resulting map. let input = Map [ (1, "a"); (2, "b") ] input |> Map.add 3 "c" // evaluates to map [(1, "a"); (2, "b"); (3, "c")] input |> Map.add 2 "aa" // evaluates to map [(1, "a"); (2, "aa")] Contains operations for working with values of type . Returns a new set with the elements of the second set removed from the first. The first input set. The set whose elements will be removed from set1. The set with the elements of set2 removed from set1. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(2).Add(3).Add(4) printfn $"The difference of {set1} and {set2} is {Set.difference set1 set2}" The sample evaluates to the following output: The difference of set [1; 2; 3] and set [2; 3; 4] is set [1] Builds a new collection from the given enumerable object. The input sequence. The set containing elements. let set = Set.ofSeq [1, 2, 3] printfn $"The set is {set} and type is {set.GetType().Name}" The sample evaluates to the following output: The set is set [(1, 2, 3)] and type is "FSharpSet`1" Returns an ordered view of the collection as an enumerable object. The input set. An ordered sequence of the elements of set. let set = Set.empty.Add(1).Add(2).Add(3) let seq = Set.toSeq set printfn $"The set is {set} and type is {seq.GetType().Name}" The sample evaluates to the following output: he set is set [1; 2; 3] and type is Microsoft.FSharp.Collections.FSharpSet`1[System.Int32] Builds an array that contains the elements of the set in order. The input set. An ordered array of the elements of set. let set = Set.empty.Add(1).Add(2).Add(3) let array = Set.toArray set printfn$ "The set is {set} and type is {array.GetType().Name}" The sample evaluates to the following output: The set is [|1; 2; 3|] and type is System.Int32 array Builds a set that contains the same elements as the given array. The input array. A set containing the elements of array. let set = Set.ofArray [|1, 2, 3|] printfn $"The set is {set} and type is {set.GetType().Name}" The sample evaluates to the following output: The set is set [(1, 2, 3)] and type is "FSharpSet`1" Builds a list that contains the elements of the set in order. The input set. An ordered list of the elements of set. let set = Set.empty.Add(1).Add(2).Add(3) let list = Set.toList set printfn $"The set is {list} and type is {list.GetType().Name}" The sample evaluates to the following output: The set is [1; 2; 3] and type is "FSharpList`1" Builds a set that contains the same elements as the given list. The input list. A set containing the elements form the input list. let set = Set.ofList [1, 2, 3] printfn $"The set is {set} and type is {set.GetType().Name}" The sample evaluates to the following output: The set is set [(1, 2, 3)] and type is "FSharpSet`1" Returns the highest element in the set according to the ordering being used for the set. The input set. The max value from the set. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The min element of {set} is {Set.minElement set}" The sample evaluates to the following output: The max element of set [1; 2; 3] is 3 Returns the lowest element in the set according to the ordering being used for the set. The input set. The min value from the set. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The min element of {set} is {Set.minElement set}" The sample evaluates to the following output: The min element of set [1; 2; 3] is 1 Returns a new set with the given element removed. No exception is raised if the set doesn't contain the given element. The element to remove. The input set. The input set with value removed. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The set without 1 is {Set.remove 1 set}" The sample evaluates to the following output: The set without 1 is set [2; 3] Splits the set into two sets containing the elements for which the given predicate returns true and false respectively. The function to test set elements. The input set. A pair of sets with the first containing the elements for which predicate returns true and the second containing the elements for which predicate returns false. let set = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"The set with even numbers is {Set.partition (fun x -> x % 2 = 0) set}" The sample evaluates to the following output: The partitioned sets are: (set [2; 4], set [1; 3]) Applies the given function to each element of the set, in order according to the comparison function. The function to apply to each element. The input set. let set = Set.empty.Add(1).Add(2).Add(3) Set.iter (fun x -> printfn $"The set contains {x}") set The sample evaluates to the following output: The set contains 1 The set contains 2 The set contains 3 Returns "true" if the set is empty. The input set. True if set is empty. let set = Set.empty.Add(2).Add(3) printfn $"Is the set empty? {set.IsEmpty}" The sample evaluates to the following output: Is the set empty? false Computes the union of a sequence of sets. The sequence of sets to union. The union of the input sets. let headersByFile = seq{ yield [ "id"; "name"; "date"; "color" ] yield [ "id"; "age"; "date" ] yield [ "id"; "sex"; "date"; "animal" ] } headersByFile |> Seq.map Set.ofList |> Set.intersectMany |> printfn "The intersection of %A is %A" headersByFile The sample evaluates to the following output: The union of seq [["id"; "name"; "date"; "color"]; ["id"; "age"; "date"]; ["id"; "sex"; "date"; "animal"]] is set ["age"; "animal"; "color"; "date"; "id"; "name"; "sex"] Computes the union of the two sets. The first input set. The second input set. The union of set1 and set2. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(2).Add(3).Add(4) printfn $"The union of {set1} and {set2} is {(Set.union set1 set2)}" The sample evaluates to the following output: The union of set [1; 2; 3] and set [2; 3; 4] is set [1; 2; 3; 4] Computes the intersection of a sequence of sets. The sequence must be non-empty. The sequence of sets to intersect. The intersection of the input sets. let headersByFile = seq{ yield [ "id"; "name"; "date"; "color" ] yield [ "id"; "age"; "date" ] yield [ "id"; "sex"; "date"; "animal" ] } headersByFile |> Seq.map Set.ofList |> Set.intersectMany |> printfn "The intersection of %A is %A" headersByFile The sample evaluates to the following output: The intersection of seq [["id"; "name"; "date"; "color"]; ["id"; "age"; "date"]; ["id"; "sex"; "date"; "animal"]] is set ["date"; "id"] Computes the intersection of the two sets. The first input set. The second input set. The intersection of set1 and set2. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(2).Add(3).Add(4) printfn $"The intersection of {set1} and {set2} is {Set.intersect set1 set2}" The sample evaluates to the following output: The intersection of set [1; 2; 3] and set [2; 3; 4] is set [2; 3] Tests if all elements of the collection satisfy the given predicate. If the input function is f and the elements are i0...iN and "j0...jN" then computes p i0 && ... && p iN. The function to test set elements. The input set. True if all elements of set satisfy predicate. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"Does the set contain even numbers? {Set.forall (fun x -> x % 2 = 0) set}" The sample evaluates to the following output: Does the set contain even numbers? false Applies the given accumulating function to all the elements of the set. The accumulating function. The input set. The initial state. The final state. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The sum of the set is {Set.foldBack (+) set 0}" printfn $"The set is {Set.foldBack (fun x acc -> x :: acc) set []}" The sample evaluates to the following output: The sum of the set is 6 The set is [1; 2; 3] Applies the given accumulating function to all the elements of the set The accumulating function. The initial state. The input set. The final state. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The sum of the set is {Set.fold (+) 0 set}" printfn $"The product of the set is {Set.fold (*) 1 set}" printfn $"The reverse of the set is {Set.fold (fun x y -> y :: x) [] set}" The sample evaluates to the following output: The sum of the set is 6 The product of the set is 6 The reverse of the set is [3; 2; 1] Returns a new collection containing the results of applying the given function to each element of the input set. The function to transform elements of the input set. The input set. A set containing the transformed elements. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The set with doubled values is {Set.map (fun x -> x * 2) set}" The sample evaluates to the following output: The set with doubled values is set [2; 4; 6] Returns a new collection containing only the elements of the collection for which the given predicate returns True. The function to test set elements. The input set. The set containing only the elements for which predicate returns true. let set = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"The set with even numbers is {Set.filter (fun x -> x % 2 = 0) set}" The sample evaluates to the following output: The set with even numbers is set [2; 4] Tests if any element of the collection satisfies the given predicate. If the input function is predicate and the elements are i0...iN then computes p i0 or ... or p iN. The function to test set elements. The input set. True if any element of set satisfies predicate. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"Does the set contain 1? {Set.exists (fun x -> x = 1) set}" The sample evaluates to the following output: Does the set contain 1? true Returns the number of elements in the set. Same as size. The input set. The number of elements in the set. let set = Set.empty.Add(1).Add(2).Add(3) printfn $"The set has {set.Count} elements" The sample evaluates to the following output: The set has 3 elements Evaluates to "true" if all elements of the second set are in the first, and at least one element of the first is not in the second. The potential superset. The set to test against. True if set1 is a proper superset of set2. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a proper superset of {set2}? {Set.isProperSuperset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a proper superset of set [1; 2; 3; 4]? false Evaluates to "true" if all elements of the second set are in the first. The potential superset. The set to test against. True if set1 is a superset of set2. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a superset of {set2}? {Set.isSuperset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a superset of set [1; 2; 3; 4]? false Evaluates to "true" if all elements of the first set are in the second, and at least one element of the second is not in the first. The potential subset. The set to test against. True if set1 is a proper subset of set2. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a proper subset of {set2}? {Set.isProperSubset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a proper subset of set [1; 2; 3; 4]? true Evaluates to "true" if all elements of the first set are in the second The potential subset. The set to test against. True if set1 is a subset of set2. let set1 = Set.empty.Add(1).Add(2).Add(3) let set2 = Set.empty.Add(1).Add(2).Add(3).Add(4) printfn $"Is {set1} a subset of {set2}? {Set.isSubset set1 set2}" The sample evaluates to the following output: Is set [1; 2; 3] a subset of set [1; 2; 3; 4]? true Evaluates to "true" if the given element is in the given set. The element to test. The input set. True if element is in set. let set = Set.empty.Add(2).Add(3) printfn $"Does the set contain 1? {set.Contains(1))}" The sample evaluates to the following output: Does the set contain 1? false Returns a new set with an element added to the set. No exception is raised if the set already contains the given element. The value to add. The input set. A new set containing value. let set = Set.empty.Add(1).Add(1).Add(2) printfn $"The new set is: {set}" The sample evaluates to the following output: The new set is: set [1; 2] The set containing the given element. The value for the set to contain. The set containing value. Set.singleton 7 Evaluates to set [ 7 ]. The empty set for the type 'T. Set.empty<int> Evaluates to set [ ]. Contains operations for working with values of type . Returns a representing an F# tuple type with the given element types Runtime assembly containing System.Tuple definitions. An array of types for the tuple elements. The type representing the tuple containing the input elements. Returns a representing an F# tuple type with the given element types An array of types for the tuple elements. The type representing the tuple containing the input elements. Returns a representing an F# struct tuple type with the given element types An array of types for the tuple elements. The type representing the struct tuple containing the input elements. Returns a representing an F# struct tuple type with the given element types Runtime assembly containing System.ValueTuple definitions. An array of types for the tuple elements. The type representing the struct tuple containing the input elements. Returns a representing the F# function type with the given domain and range The input type of the function. The output type of the function. The function type with the given domain and range. Returns true if the typ is a representation of an F# union type or the runtime type of a value of that type The type to check. Optional binding flags. True if the type check succeeds. Return true if the typ is a representation of an F# tuple type The type to check. True if the type check succeeds. Return true if the typ is a representation of an F# record type The type to check. Optional binding flags. True if the type check succeeds. Return true if the typ is a value corresponding to the compiled form of an F# module The type to check. True if the type check succeeds. Return true if the typ is a representation of an F# function type or the runtime type of a closure implementing an F# function type The type to check. True if the type check succeeds. Returns true if the typ is a representation of an F# exception declaration The type to check. Optional binding flags. True if the type check is an F# exception. Gets the cases of a union type. Assumes the given type is a union type. If not, is raised during pre-computation. The input union type. Optional binding flags. Thrown when the input type is not a union type. An array of descriptions of the cases of the given union type. Gets the tuple elements from the representation of an F# tuple type. The input tuple type. An array of the types contained in the given tuple type. Reads all the fields from a record value, in declaration order Assumes the given input is a record value. If not, is raised. The input record type. Optional binding flags. An array of descriptions of the properties of the record type. Gets the domain and range types from an F# function type or from the runtime type of a closure implementing an F# type The input function type. A tuple of the domain and range types of the input function. Reads all the fields from an F# exception declaration, in declaration order Assumes exceptionType is an exception representation type. If not, is raised. The exception type to read. Optional binding flags. Thrown if the given type is not an exception. An array containing the PropertyInfo of each field in the exception. Contains operations associated with constructing and analyzing F# types such as records, unions and tuples Assumes the given type is a union type. If not, is raised during pre-computation. Using the computed function is more efficient than calling GetUnionCase because the path executed by the computed function is optimized given the knowledge that it will be used to read values of the given type. The type of union to optimize reading. Optional binding flags. An optimized function to read the tags of the given union type. Precompute a property or static method for reading an integer representing the case tag of a union type. The type of union to read. Optional binding flags. The description of the union case reader. Precompute a function for reading all the fields for a particular discriminator case of a union type Using the computed function will typically be faster than executing a corresponding call to GetFields The description of the union case to read. Optional binding flags. A function to for reading the fields of the given union case. A method that constructs objects of the given case The description of the union case. Optional binding flags. The description of the constructor of the given union case. Precompute a function for constructing a discriminated union value for a particular union case. The description of the union case. Optional binding flags. A function for constructing values of the given union case. Precompute a function for reading the values of a particular tuple type Assumes the given type is a TupleType. If not, is raised during pre-computation. The tuple type to read. Thrown when the given type is not a tuple type. A function to read values of the given tuple type. Gets information that indicates how to read a field of a tuple The input tuple type. The index of the tuple element to describe. The description of the tuple element and an optional type and index if the tuple is big. Gets a method that constructs objects of the given tuple type. For small tuples, no additional type will be returned. For large tuples, an additional type is returned indicating that a nested encoding has been used for the tuple type. In this case the suffix portion of the tuple type has the given type and an object of this type must be created and passed as the last argument to the ConstructorInfo. A recursive call to PreComputeTupleConstructorInfo can be used to determine the constructor for that the suffix type. The input tuple type. The description of the tuple type constructor and an optional extra type for large tuples. Precompute a function for reading the values of a particular tuple type Assumes the given type is a TupleType. If not, is raised during pre-computation. The type of tuple to read. Thrown when the given type is not a tuple type. A function to read a particular tuple type. Precompute a function for reading all the fields from a record. The fields are returned in the same order as the fields reported by a call to Microsoft.FSharp.Reflection.Type.GetInfo for this type. Assumes the given type is a RecordType. If not, is raised during pre-computation. Using the computed function will typically be faster than executing a corresponding call to Value.GetInfo because the path executed by the computed function is optimized given the knowledge that it will be used to read values of the given type. The type of record to read. Optional binding flags. Thrown when the input type is not a record type. An optimized reader for the given record type. Precompute a function for reading a particular field from a record. Assumes the given type is a RecordType with a field of the given name. If not, is raised during pre-computation. Using the computed function will typically be faster than executing a corresponding call to Value.GetInfo because the path executed by the computed function is optimized given the knowledge that it will be used to read values of the given type. The PropertyInfo of the field to read. Thrown when the input type is not a record type. A function to read the specified field from the record. Get a ConstructorInfo for a record type The record type. Optional binding flags. A ConstructorInfo for the given record type. Precompute a function for constructing a record value. Assumes the given type is a RecordType. If not, is raised during pre-computation. The type of record to construct. Optional binding flags. Thrown when the input type is not a record type. A function to construct records of the given type. Create a union case value. The description of the union case to create. The array of arguments to construct the given case. Optional binding flags. The constructed union case. Creates an instance of a tuple type Assumes at least one element is given. If not, is raised. The array of tuple fields. The tuple type to create. Thrown if no elements are given. An instance of the tuple type with the given elements. Creates an instance of a record type. Assumes the given input is a record type. The type of record to make. The array of values to initialize the record. Optional binding flags for the record. Thrown when the input type is not a record type. The created record. Builds a typed function from object from a dynamic function implementation The function type of the implementation. The untyped lambda of the function implementation. A typed function from the given dynamic implementation. Identify the union case and its fields for an object Assumes the given input is a union case value. If not, is raised. If the type is not given, then the runtime type of the input object is used to identify the relevant union type. The type should always be given if the input object may be null. For example, option values may be represented using the 'null'. The input union case. The union type containing the value. Optional binding flags. Thrown when the input type is not a union case value. The description of the union case and its fields. Reads all fields from a tuple. Assumes the given input is a tuple value. If not, is raised. The input tuple. Thrown when the input is not a tuple value. An array of the fields from the given tuple. Reads a field from a tuple value. Assumes the given input is a tuple value. If not, is raised. The input tuple. The index of the field to read. The value of the field. Reads all the fields from a record value. Assumes the given input is a record value. If not, is raised. The record object. Optional binding flags for the record. Thrown when the input type is not a record type. The array of fields from the record. Reads a field from a record value. Assumes the given input is a record value. If not, is raised. The record object. The PropertyInfo describing the field to read. Thrown when the input is not a record value. The field from the record. Reads all the fields from a value built using an instance of an F# exception declaration Assumes the given input is an F# exception value. If not, is raised. The exception instance. Optional binding flags. Thrown when the input type is not an F# exception. The fields from the given exception. Contains operations associated with constructing and analyzing values associated with F# types such as records, unions and tuples. The integer tag for the case. type CoinToss = Heads | Tails typeof<CoinToss> |> FSharpType.GetUnionCases |> Array.map (fun x -> $"{x.Name} has tag {x.Tag}") Evaluates to [|"Heads has tag 0"; "Tails has tag 1"|] The name of the case. type Weather = Rainy | Sunny typeof<Weather> |> FSharpType.GetUnionCases |> Array.map (fun x -> x.Name) Evaluates to [|"Rainy", "Sunny"|] The type in which the case occurs. type Weather = Rainy | Sunny let rainy = typeof<Weather> |> FSharpType.GetUnionCases |> Array.head rainy.DeclaringType Evaluates to a value of type System.Type that holds type information for Weather. The fields associated with the case, represented by a PropertyInfo. The fields associated with the case. type Shape = | Rectangle of width : float * length : float | Circle of radius : float | Prism of width : float * float * height : float typeof<Shape> |> FSharpType.GetUnionCases |> Array.map (fun unionCase -> unionCase.GetFields() |> Array.map (fun fieldInfo -> fieldInfo.Name, fieldInfo.PropertyType.Name)) Evaluates to [|[|("width", "Double"); ("length", "Double")|]; [|("radius", "Double")|]; [|("width", "Double"); ("Item2", "Double"); ("height", "Double")|]|] Returns the custom attributes data associated with the case. An list of custom attribute data items. type Signal(signal: string) = inherit System.Attribute() member this.Signal = signal type Answer = | [<Signal("Thumbs up")>] Yes | [<Signal("Thumbs down")>] No let answerYes = typeof<Answer> |> FSharpType.GetUnionCases |> Array.find (fun x -> x.Name = "Yes") answerYes.GetCustomAttributesData() Evaluates to [|[FSI_0150+Signal("Thumbs up")] {AttributeType = FSI_0150+Signal; Constructor = Void .ctor(System.String); ConstructorArguments = seq ["Thumbs up"]; NamedArguments = seq [];}; [Microsoft.FSharp.Core.CompilationMappingAttribute((Microsoft.FSharp.Core.SourceConstructFlags)8, (Int32)0)] {AttributeType = Microsoft.FSharp.Core.CompilationMappingAttribute; Constructor = Void .ctor(Microsoft.FSharp.Core.SourceConstructFlags, Int32); ConstructorArguments = seq [(Microsoft.FSharp.Core.SourceConstructFlags)8; (Int32)0]; NamedArguments = seq [];}|] Returns the custom attributes associated with the case matching the given attribute type. The type of attributes to return. An array of custom attributes. type Signal(signal: string) = inherit System.Attribute() member this.Signal = signal type Answer = | [<Signal("Thumbs up")>] Yes | [<Signal("Thumbs down")>] No typeof<Answer> |> FSharpType.GetUnionCases |> Array.map (fun x -> x.GetCustomAttributes(typeof<Signal>)) Evaluates to [|[|FSI_0147+Signal {Signal = "Thumbs up"; TypeId = FSI_0147+Signal;}|]; [|FSI_0147+Signal {Signal = "Thumbs down"; TypeId = FSI_0147+Signal;}|]|] Returns the custom attributes associated with the case. An array of custom attributes. type Weather = | Rainy | Sunny typeof<Weather> |> FSharpType.GetUnionCases |> Array.map (fun x -> x.GetCustomAttributes()) Evaluates to [|[|Microsoft.FSharp.Core.CompilationMappingAttribute {ResourceName = null; SequenceNumber = 0; SourceConstructFlags = UnionCase; TypeDefinitions = null; TypeId = Microsoft.FSharp.Core.CompilationMappingAttribute; VariantNumber = 0;}|]; [|Microsoft.FSharp.Core.CompilationMappingAttribute {ResourceName = null; SequenceNumber = 1; SourceConstructFlags = UnionCase; TypeDefinitions = null; TypeId = Microsoft.FSharp.Core.CompilationMappingAttribute; VariantNumber = 0;}|]|] Represents a case of a discriminated union type Library functionality for accessing additional information about F# types and F# values at runtime, augmenting that available through System.Reflection. Returns true if the exceptionType is a representation of an F# exception declaration The type to check. Optional flag that denotes accessibility of the private representation. True if the type check is an F# exception. Reads all the fields from an F# exception declaration, in declaration order Assumes exceptionType is an exception representation type. If not, is raised. The exception type to read. Optional flag that denotes accessibility of the private representation. Thrown if the given type is not an exception. An array containing the PropertyInfo of each field in the exception. Returns true if the typ is a representation of an F# union type or the runtime type of a value of that type The type to check. Optional flag that denotes accessibility of the private representation. True if the type check succeeds. Return true if the typ is a representation of an F# record type The type to check. Optional flag that denotes accessibility of the private representation. True if the type check succeeds. Gets the cases of a union type. Assumes the given type is a union type. If not, is raised during pre-computation. The input union type. Optional flag that denotes accessibility of the private representation. Thrown when the input type is not a union type. An array of descriptions of the cases of the given union type. Reads all the fields from a record value, in declaration order Assumes the given input is a record value. If not, is raised. The input record type. Optional flag that denotes accessibility of the private representation. An array of descriptions of the properties of the record type. Reads all the fields from a value built using an instance of an F# exception declaration Assumes the given input is an F# exception value. If not, is raised. The exception instance. Optional flag that denotes accessibility of the private representation. Thrown when the input type is not an F# exception. The fields from the given exception. A method that constructs objects of the given case The description of the union case. Optional flag that denotes accessibility of the private representation. The description of the constructor of the given union case. Precompute a function for constructing a discriminated union value for a particular union case. The description of the union case. Optional flag that denotes accessibility of the private representation. A function for constructing values of the given union case. Precompute a function for reading all the fields for a particular discriminator case of a union type Using the computed function will typically be faster than executing a corresponding call to GetFields The description of the union case to read. Optional flag that denotes accessibility of the private representation. A function to for reading the fields of the given union case. Precompute a property or static method for reading an integer representing the case tag of a union type. The type of union to read. Optional flag that denotes accessibility of the private representation. The description of the union case reader. Assumes the given type is a union type. If not, is raised during pre-computation. Using the computed function is more efficient than calling GetUnionCase because the path executed by the computed function is optimized given the knowledge that it will be used to read values of the given type. The type of union to optimize reading. Optional flag that denotes accessibility of the private representation. An optimized function to read the tags of the given union type. Identify the union case and its fields for an object Assumes the given input is a union case value. If not, is raised. If the type is not given, then the runtime type of the input object is used to identify the relevant union type. The type should always be given if the input object may be null. For example, option values may be represented using the 'null'. The input union case. The union type containing the value. Optional flag that denotes accessibility of the private representation. Thrown when the input type is not a union case value. The description of the union case and its fields. Create a union case value. The description of the union case to create. The array of arguments to construct the given case. Optional flag that denotes accessibility of the private representation. The constructed union case. Get a ConstructorInfo for a record type The record type. Optional flag that denotes accessibility of the private representation. A ConstructorInfo for the given record type. Precompute a function for constructing a record value. Assumes the given type is a RecordType. If not, is raised during pre-computation. The type of record to construct. Optional flag that denotes accessibility of the private representation. Thrown when the input type is not a record type. A function to construct records of the given type. Precompute a function for reading all the fields from a record. The fields are returned in the same order as the fields reported by a call to Microsoft.FSharp.Reflection.Type.GetInfo for this type. Assumes the given type is a RecordType. If not, is raised during pre-computation. Using the computed function will typically be faster than executing a corresponding call to Value.GetInfo because the path executed by the computed function is optimized given the knowledge that it will be used to read values of the given type. The type of record to read. Optional flag that denotes accessibility of the private representation. Thrown when the input type is not a record type. An optimized reader for the given record type. Reads all the fields from a record value. Assumes the given input is a record value. If not, is raised. The record object. Optional flag that denotes accessibility of the private representation. Thrown when the input type is not a record type. The array of fields from the record. Creates an instance of a record type. Assumes the given input is a record type. The type of record to make. The array of values to initialize the record. Optional flags that denotes accessibility of the private representation. Thrown when the input type is not a record type. The created record. Defines further accessing additional information about F# types and F# values at runtime. A record of options to control structural formatting. For F# Interactive properties matching those of this value can be accessed via the 'fsi' value. Floating Point format given in the same format accepted by System.Double.ToString, e.g. f6 or g15. If ShowProperties is set the printing process will evaluate properties of the values being displayed. This may cause additional computation. The ShowIEnumerable is set the printing process will force the evaluation of IEnumerable objects to a small, finite depth, as determined by the printing parameters. This may lead to additional computation being performed during printing. Data representing structured layouts of terms. Convert any value to a layout using the given formatting options. The layout can then be processed using formatting display engines such as those in the Layout module. any_to_string and output_any are built using any_to_layout with default format options. For limiting layout of list-like sequences (lists,arrays,etc). unfold a list of items using (project and z) making layout list via itemL. If reach maxLength (before exhausting) then truncate. See tagL Layout like an F# list. Layout like an F# option. Layout list vertically. Layout two vertically. Form tuple of layouts. Wrap braces around layout. Wrap square brackets around layout. Wrap round brackets around Layout. Join layouts into a list separated using the given Layout. Join layouts into a semi-colon separated list. Join layouts into a space separated list. Join layouts into a comma separated list. Join broken with ident=4 Join broken with ident=3 Join broken with ident=2 Join broken with ident=1 Join broken with ident=0 optional break, indent=4 optional break, indent=3 Join, possible break with indent=2 Join, possible break with indent=1 Join, possible break with indent=0 Join, unbreakable. An string which is left parenthesis (no space on the right). An string which is right parenthesis (no space on the left). An string which requires no spaces either side. An string leaf An uninterpreted leaf, to be interpreted into a string by the layout engine. This allows leaf layouts for numbers, strings and other atoms to be customized according to culture. Is it the empty layout? The empty layout A layout is a sequence of strings which have been joined together. The strings are classified as words, separators and left and right parenthesis. This classification determines where spaces are inserted. A joint is either unbreakable, breakable or broken. If a joint is broken the RHS layout occurs on the next line with optional indentation. A layout can be squashed to for given width which forces breaks as required. Gets the raw expression associated with this type-carrying expression open FSharp.Quotations let expr1 = <@ 1 + 1 @> expr1.Raw Evaluates to the same quotation as <@ expr1 @> except with the weaker type Expr instead of Expr<int>. Type-carrying quoted expressions. Expressions are generated either by quotations in source text or programmatically Returns type of an expression. open FSharp.Quotations open FSharp.Quotations.Patterns let sampleQuotation = <@ 1 + 1 @> sampleQuotation.Type Evaluates to typeof<int>. Returns the custom attributes of an expression. For quotations deriving from quotation literals this may include the source location of the literal. open FSharp.Quotations open FSharp.Quotations.Patterns let sampleQuotation = <@ 1 + 1 @> sampleQuotation.CustomAttributes Evaluates to a list of expressions containing one custom attribute for the source location of the quotation literal. Builds an expression that represents a value and its associated reflected definition as a quotation The untyped object. The type of the object. The definition of the value being quoted. The resulting expression. open FSharp.Quotations Expr.WithValue(box 1, typeof<int>, <@ 2 - 1 @>) Evaluates to a quotation that displays as WithValue (1, Call (None, op_Subtraction, [Value (2), Value (1)])). Builds an expression that represents a value and its associated reflected definition as a quotation The value being quoted. The definition of the value being quoted. The resulting expression. open FSharp.Quotations Expr.WithValue(1, <@ 2 - 1 @>) Evaluates to a quotation that displays as WithValue (1, Call (None, op_Subtraction, [Value (2), Value (1)])). Builds an expression that represents a while loop The predicate to control the loop iteration. The body of the while loop. The resulting expression. open FSharp.Quotations let guardExpr = <@ true @> let bodyExpr = <@ () @> Expr.WhileLoop(guardExpr, bodyExpr) Evaluates to a quotation with the same structure as <@ while true do () @>. Builds an expression that represents setting a mutable variable The input variable. The value to set. The resulting expression. open FSharp.Quotations let vVar = Var("v", typeof<int>, isMutable=true) Expr.VarSet(vVar, <@ 5 @>) Evaluates to a quotation displayed as VarSet (v, Value (5)). Builds an expression that represents a variable The input variable. The resulting expression. open FSharp.Quotations let vVar = Var("v", typeof<int>) Expr.Var(vVar) Evaluates to a quotation displayed as v. Builds an expression that represents a constant value of a particular type, arising from a variable of the given name The untyped object. The type of the object. The name of the variable. The resulting expression. open FSharp.Quotations Expr.ValueWithName(box 1, typeof<int>, "name") Evaluates to a quotation with the same structure as <@ 1 @> and associated information that the name of the value is "name". Builds an expression that represents a constant value, arising from a variable of the given name The typed value. The name of the variable. The resulting expression. open FSharp.Quotations Expr.ValueWithName(1, "name") Evaluates to a quotation with the same structure as <@ 1 @> and associated information that the name of the value is "name". Builds an expression that represents a constant value The typed value. open FSharp.Quotations Expr.Value(1) Evaluates to a quotation with the same structure as <@ 1 @>. Builds an expression that represents a constant value of a particular type The untyped object. The type of the object. The resulting expression. open FSharp.Quotations Expr.Value(box 1, typeof<int>) Evaluates to a quotation with the same structure as <@ 1 @>. Builds an expression that represents a test of a value is of a particular union case The expression to test. The description of the union case. The resulting expression. open System open FSharp.Quotations open FSharp.Reflection let ucCons = FSharpType.GetUnionCases(typeof<int list>)[1] Expr.UnionCaseTest(<@ [11] @>, ucCons) Evaluates to a quotation that displays as UnionCaseTest (NewUnionCase (Cons, Value (11), NewUnionCase (Empty)), Cons). Builds an expression that represents a type test. The expression to test. The target type. The resulting expression. open FSharp.Quotations let obj = box 1 Expr.TypeTest( <@ obj @>, typeof<int>) Evaluates to quotation that displays as TypeTest (Int32, PropertyGet (None, obj, [])). Builds an expression that represents getting a field of a tuple The input tuple. The index of the tuple element to get. The resulting expression. open FSharp.Quotations let tupExpr = <@ (1, 2, 3) @> Expr.TupleGet(tupExpr, 1) Evaluates to quotation that displays as TupleGet (NewTuple (Value (1), Value (2), Value (3)), 1). Builds an expression that represents a try/with construct for exception filtering and catching. The body of the try expression. The variable to bind to a caught exception. The expression evaluated when an exception is caught. The resulting expression. open System open FSharp.Quotations let exnVar = Var("exn", typeof<exn>) Expr.TryWith(<@ 1+1 @>, exnVar, <@ 1 @>, exnVar, <@ 2+2 @>) Evaluates to a quotation with the same structure as <@ try 1+1 with exn -> 2+2 @>. Try and find a stored reflection definition for the given method. Stored reflection definitions are added to an F# assembly through the use of the [<ReflectedDefinition>] attribute. The description of the method to find. The reflection definition or None if a match could not be found. open FSharp.Quotations open FSharp.Quotations.Patterns [<ReflectedDefinition>] let f x = x + 1 let methInfo = match <@ f 1 @> with | Call(_, mi, _) -> mi | _ -> failwith "call expected" Expr.TryGetReflectedDefinition(methInfo) Evaluates to a quotation with the same structure as <@ fun x -> x + 1 @>, which is the implementation of the method f. open FSharp.Quotations open FSharp.Quotations.Patterns [<ReflectedDefinition>] module Methods = let f x = (x, x) let methInfoGeneric = match <@ Methods.f (1, 2) @> with | Call(_, mi, _) -> mi.GetGenericMethodDefinition() | _ -> failwith "call expected" let methInfoAtString = methInfoGeneric.MakeGenericMethod(typeof<string>) Expr.TryGetReflectedDefinition(methInfoAtString) Evaluates to a quotation with the same structure as <@ fun (x: string) -> (x, x) @>, which is the implementation of the generic method f instantiated at type string. Builds an expression that represents a try/finally construct The body of the try expression. The final part of the expression to be evaluated. The resulting expression. open System open FSharp.Quotations Expr.TryFinally(<@ 1+1 @>, <@ Console.WriteLine("finally") @>) Evaluates to a quotation with the same structure as <@ try 1+1 finally Console.WriteLine("finally") @>. Format the expression as a string Indicates if method, property, constructor and type objects should be printed in detail. If false, these are abbreviated to their name. The formatted string. open FSharp.Quotations let expr1 = <@ 1 + 1 @> expr1.ToString(true) Evaluates "Call (None, Int32 op_Addition[Int32,Int32,Int32](Int32, Int32),[Value (1), Value (1)])". Substitutes through the given expression using the given functions to map variables to new values. The functions must give consistent results at each application. Variable renaming may occur on the target expression if variable capture occurs. The function to map variables into expressions. The expression with the given substitutions. open FSharp.Quotations open FSharp.Quotations.Patterns let sampleQuotation = <@ fun v -> v * v @> let v, body = match sampleQuotation with | Lambda(v, body) -> (v, body) | _ -> failwith "unreachable" body.Substitute(function v2 when v = v2 -> Some <@ 1 + 1 @> | _ -> None) Evaluates to <@ (1 + 1) * (1 + 1)>. Builds an expression that represents the sequential execution of one expression followed by another The first expression. The second expression. The resulting expression. open System open FSharp.Quotations Expr.Sequential(<@ Console.WriteLine("a") @>, <@ Console.WriteLine("b") @>) Evaluates to a quotation with the same structure as <@ Console.WriteLine("a"); Console.WriteLine("b") @>. Permits interactive environments such as F# Interactive to explicitly register new pickled resources that represent persisted top level definitions. The assembly associated with the resource. The unique name for the resources being added. The type definitions referenced. The serialized resource to register with the environment. Permits interactive environments such as F# Interactive to explicitly register new pickled resources that represent persisted top level definitions. The assembly associated with the resource. The unique name for the resources being added. The serialized resource to register with the environment. Builds an expression that represents a nested typed quotation literal The expression being quoted. The resulting expression. open FSharp.Quotations Expr.QuoteTyped(<@ 1 @>) Evaluates to a quotation with the same structure as <@ <@ 1 @> @>. Builds an expression that represents a nested raw quotation literal The expression being quoted. The resulting expression. open FSharp.Quotations Expr.QuoteRaw(<@ 1 @>) Evaluates to a quotation with the same structure as <@ <@ 1 @> @>. Builds an expression that represents a nested typed or raw quotation literal The expression being quoted. The resulting expression. Builds an expression that represents writing to a static property The description of the property. The value to set. List of indices for the property if it is an indexed property. The resulting expression. open System open System.Collections.Generic open FSharp.Quotations open FSharp.Quotations.Patterns let propInfo = match <@ Console.BackgroundColor <- ConsoleColor.Red @> with | PropertySet(None, pi, _, _) -> pi | _ -> failwith "property get expected" Expr.PropertySet(propInfo, <@ ConsoleColor.Blue @>) Evaluates to a quotation with the same structure as <@ Console.BackgroundColor <- ConsoleColor.Blue @>. Builds an expression that represents writing to a property of an object The input object. The description of the property. The value to set. List of indices for the property if it is an indexed property. The resulting expression. open System open System.Collections.Generic open FSharp.Quotations open FSharp.Quotations.Patterns let propInfo = match <@ (new List<int>()).Capacity @> with | PropertyGet(Some _, pi, _) -> pi | _ -> failwith "property get expected" let objExpr = <@ (new List<int>()) @> Expr.PropertySet(objExpr, propInfo, <@ 6 @>) Evaluates to a quotation with the same structure as <@ (new List<int>()).Capacity <- 6 @>. Builds an expression that represents reading a static property The description of the property. List of indices for the property if it is an indexed property. The resulting expression. open System open FSharp.Quotations open FSharp.Quotations.Patterns let propInfo = match <@ Console.Out @> with | PropertyGet(None, pi, _) -> pi | _ -> failwith "property get expected" Expr.PropertyGet(propInfo) Evaluates to a quotation with the same structure as <@ Console.Out @>. Builds an expression that represents reading a property of an object The input object. The description of the property. List of indices for the property if it is an indexed property. The resulting expression. open System open FSharp.Quotations open FSharp.Quotations.Patterns let propInfo = match <@ "a".Length @> with | PropertyGet(Some _, pi, _) -> pi | _ -> failwith "property get expected" let objExpr = <@ "bb" @> Expr.PropertyGet(objExpr, propInfo) Evaluates to a quotation with the same structure as <@ "bb".Length @>. Builds an expression that represents the creation of a union case value The description of the union case. The list of arguments for the case. The resulting expression. open System open FSharp.Quotations open FSharp.Reflection let ucCons = FSharpType.GetUnionCases(typeof<int list>)[1] Expr.NewUnionCase(ucCons, [ <@ 10 @>; <@ [11] @> ]) Evaluates to a quotation with the same structure as <@ 10 :: [11] @>. Builds an expression that represents the creation of an F# tuple value The list of elements of the tuple. The resulting expression. open FSharp.Quotations Expr.NewTuple([ <@ 1 @>; <@ "a" @> ]) Evaluates to a quotation with the same structure as <@ (1, "a") @>. Builds an expression that represents the creation of an F# tuple value The list of elements of the tuple. The resulting expression. open FSharp.Quotations Expr.NewStructTuple( [ <@ 1 @>; <@ "a" @> ]) Evaluates to a quotation with the same structure as <@ struct (1, "a") @>. Builds an expression that represents the creation of an F# tuple value Runtime assembly containing System.ValueTuple definitions. The list of elements of the tuple. The resulting expression. open FSharp.Quotations Expr.NewStructTuple(typeof<struct (int * int)>.Assembly, [ <@ 1 @>; <@ "a" @> ]) Evaluates to a quotation with the same structure as <@ struct (1, "a") @>. Builds record-construction expressions The type of record. The list of elements of the record. The resulting expression. open FSharp.Quotations type R = { Y: int; X: string } Expr.NewRecord(typeof<R>, [ <@ 1 @>; <@ "a" @> ]) Evaluates to a quotation with the same structure as <@ { Y = 1; X = "a" } @>. Builds an expression that represents the invocation of an object constructor The description of the constructor. The list of arguments to the constructor. The resulting expression. open System open FSharp.Quotations open FSharp.Quotations.Patterns let ctorInfo = match <@ new System.DateTime(100L) @> with | NewObject(ci, _) -> ci | _ -> failwith "call expected" let argExpr = <@ 100000L @> Expr.NewObject(ctorInfo, [argExpr]) Evaluates to a quotation with the same structure as <@ NewObject (DateTime, Value (100000L)) @>. Builds an expression that represents the creation of a delegate value for the given type The type of delegate. The parameters for the delegate. The body of the function. The resulting expression. open System open FSharp.Quotations let vVar = Var("v", typeof<int>) let vExpr = Expr.Var(vVar) Expr.NewDelegate(typeof<Func<int,int>>, [vVar], vExpr) Evaluates to a quotation with the same structure as <@ new System.Func<int, int>(fun v -> v) @>. Builds an expression that represents the creation of an array value initialized with the given elements The type for the elements of the array. The list of elements of the array. The resulting expression. open FSharp.Quotations Expr.NewArray(typeof<int>, [ <@ 1 @>; <@ 2 @> ]) Evaluates to a quotation with the same structure as <@ [| 1; 2 |] @>. Builds recursive expressions associated with 'let rec' constructs The list of bindings for the let expression. The sub-expression where the bindings are in scope. The resulting expression. open FSharp.Quotations open FSharp.Quotations.Patterns let fVar = Var("f", typeof<int -> int>) let gVar = Var("v", typeof<int -> int>) let fExpr = Expr.Var(fVar) let gExpr = Expr.Var(gVar) let fImplExpr = <@ fun x -> (%%gExpr : int -> int) (x - 1) + 1 @> let gImplExpr = <@ fun x -> if x > 0 then (%%fExpr : int -> int) (x - 1) else 0 @> let bodyExpr = <@ (%%gExpr : int -> int) 10 @> Expr.LetRecursive([(fVar, fImplExpr); (gVar, gImplExpr)], bodyExpr) Evaluates to a quotation with the same structure as <@ let rec f x = g (x-1) + 1 and g x = if x > 0 then f (x - 1) else 0 in g 10 @>. Builds expressions associated with 'let' constructs The variable in the let expression. The expression bound to the variable. The sub-expression where the binding is in scope. The resulting expression. open FSharp.Quotations let vVar = Var("v", typeof<int>) let rhsExpr = <@ 6 @> let vExpr = Expr.Var(vVar) Expr.Let(vVar, rhsExpr, vExpr) Evaluates to a quotation with the same structure as <@ let v = 6 in v @>. Builds an expression that represents the construction of an F# function value The parameter to the function. The body of the function. The resulting expression. open FSharp.Quotations open FSharp.Quotations.Patterns let vVar = Var("v", typeof<int>) let vExpr = Expr.Var(vVar) Expr.Lambda(vVar, vExpr) Evaluates to Lambda (v, v). Builds 'if ... then ... else' expressions. The condition expression. The then sub-expression. The else sub-expression. The resulting expression. open FSharp.Quotations let guardExpr = <@ 1 > 3 @> let thenExpr = <@ 6 @> let elseExpr = <@ 7 @> Expr.IfThenElse(guardExpr, thenExpr, elseExpr) Evaluates to a quotation with the same structure as <@ if 1 > 3 then 6 else 7 @>. Fetches or creates a new variable with the given name and type from a global pool of shared variables indexed by name and type. The type is given by the explicit or inferred type parameter The variable name. The created of fetched typed global variable. open FSharp.Quotations let expr1 = Expr.GlobalVar<int>("x") let expr2 = Expr.GlobalVar<int>("x") Evaluates expr1 and expr2 to identical quotations. Gets the free expression variables of an expression as a list. A sequence of the free variables in the expression. open FSharp.Quotations open FSharp.Quotations.Patterns let sampleQuotation = <@ fun v -> v * v @> let v, body = match sampleQuotation with | Lambda(v, body) -> (v, body) | _ -> failwith "unreachable" body.GetFreeVars() Evaluates to a set containing the single variable for v Builds a 'for i = ... to ... do ...' expression that represent loops over integer ranges The sub-expression declaring the loop variable. The sub-expression setting the initial value of the loop variable. The sub-expression declaring the final value of the loop variable. The sub-expression representing the body of the loop. The resulting expression. open FSharp.Quotations let loopVariable = Var("x", typeof<int>) let startExpr = <@ 6 @> let endExpr = <@ 7 @> let body = <@ System.Console.WriteLine("hello") @> Expr.ForIntegerRangeLoop(loopVariable, startExpr, endExpr, body) Evaluates to a quotation with the same structure as <@ for x in 6..7 do System.Console.WriteLine("hello") @>. Builds an expression that represents writing to a field of an object The input object. The description of the field to write to. The value to set to the field. The resulting expression. Create an expression setting a reference cell via the public backing field: open FSharp.Quotations open FSharp.Quotations.Patterns let fieldInfo = typeof<int ref>.GetField("contents@") let refValue = ref 3 let refExpr = <@ refValue @> let valueExpr = <@ 6 @> Expr.FieldSet(refExpr, fieldInfo, valueExpr) Evaluates to FieldSet (Some (PropertyGet (None, refValue, [])), contents@, Value (6)). Note that for technical reasons the quotation <@ refValue.contents <- 6 @> evaluates to a slightly different quotation accessing the contents field via a property. Builds an expression that represents writing to a static field The description of the field to write to. The value to the set to the field. The resulting expression. Settable public static fields are rare in F# and .NET libraries, so examples of using this method are uncommon. Builds an expression that represents the access of a field of an object The input object. The description of the field to access. The resulting expression. open FSharp.Quotations open FSharp.Quotations.Patterns let fieldInfo = typeof<int ref>.GetField("contents@") let refValue = ref 3 let refExpr = <@ refValue @> Expr.FieldGet(refExpr, fieldInfo) Evaluates to FieldGet (Some (PropertyGet (None, refValue, [])), contents@). Note that for technical reasons the quotation <@ refValue.contents @> evaluates to a different quotation accessing the contents field via a property. Builds an expression that represents the access of a static field The description of the field to access. The resulting expression. open FSharp.Quotations open FSharp.Quotations.Patterns let fieldInfo = typeof<System.DayOfWeek>.GetField("Monday") Expr.FieldGet(fieldInfo) Evaluates to FieldGet (None, Monday). Note that for technical reasons the quotation <@ System.DayOfWeek.Monday @> evaluates to a different quotation containing a constant enum value Value (Monday). This function is called automatically when quotation syntax (<@ @>) and other sources of quotations are used. A type in the assembly where the quotation occurs. The type definitions referenced. The spliced types, to replace references to type variables. The spliced expressions to replace references to spliced expressions. The serialized form of the quoted expression. The resulting expression. This function is called automatically when quotation syntax (<@ @>) and other sources of quotations are used. A type in the assembly where the quotation occurs. The spliced types, to replace references to type variables. The spliced expressions to replace references to spliced expressions. The serialized form of the quoted expression. The resulting expression. Builds an expression that represents the invocation of a default object constructor The type on which the constructor is invoked. The resulting expression. open FSharp.Quotations Expr.DefaultValue(typeof<int>) Evaluates to the quotation DefaultValue (Int32). Builds an expression that represents the coercion of an expression to a type The expression to coerce. The target type. The resulting expression. open FSharp.Quotations let expr = <@ box "3" @> Expr.Coerce(expr, typeof<string>) Evaluates to a quotation with the same structure as <@ (fun x -> x + 1) 3 @>. Returns a new typed expression given an underlying runtime-typed expression. A type annotation is usually required to use this function, and using an incorrect type annotation may result in a later runtime exception. The expression to cast. The resulting typed expression. open FSharp.Quotations let rawExpr = <@ 1 @> Expr.Cast<int>(rawExpr) Evaluates with type Expr<int>. Builds an expression that represents a call to an instance method associated with an object, potentially passing additional witness arguments The input object. The description of the method to call. The additional MethodInfo describing the method to call, accepting witnesses. The list of witnesses to the method. The list of arguments to the method. The resulting expression. See examples for Call and CallWithWitnesses Builds an expression that represents a call to an static method or module-bound function, potentially passing additional witness arguments The MethodInfo describing the method to call. The additional MethodInfo describing the method to call, accepting witnesses. The list of witnesses to the method. The list of arguments to the method. The resulting expression. In this example, we show how to use a witness to construct an `op_Addition` call for a type that doesn't support addition directly: open FSharp.Quotations open FSharp.Quotations.Patterns // Get the entrypoint for inline addition that takes an explicit witness let addMethInfoG, addMethInfoGW = match <@ 1+1 @> with | CallWithWitnesses(None, mi, miW, _, _) -> mi.GetGenericMethodDefinition(), miW.GetGenericMethodDefinition() | _ -> failwith "call expected" // Make a non-standard witness for addition for a type C type C(value: int) = member x.Value = value let witnessExpr = <@ (fun (x: C) (y: C) -> C(x.Value + y.Value)) @> let argExpr1 = <@ C(4) @> let argExpr2 = <@ C(5) @> // Instantiate the generic method at the right type let addMethInfo = addMethInfoG.MakeGenericMethod(typeof<C>, typeof<C>, typeof<C>) let addMethInfoW = addMethInfoGW.MakeGenericMethod(typeof<C>, typeof<C>, typeof<C>) Expr.CallWithWitnesses(addMethInfo, addMethInfoW, [witnessExpr], [argExpr1; argExpr2]) Evaluates to a quotation with the same structure as <@ Call (None, op_Addition, [NewObject (C, Value (4)), NewObject (C, Value (5))]) @>. Builds an expression that represents a call to an instance method associated with an object The input object. The description of the method to call. The list of arguments to the method. The resulting expression. open System open FSharp.Quotations open FSharp.Quotations.Patterns let objExpr, methInfo = match <@ Console.Out.WriteLine("1") @> with | Call(Some obj, mi, _) -> obj, mi | _ -> failwith "call expected" let argExpr = <@ "Hello World" @> Expr.Call(objExpr, methInfo, [argExpr]) Evaluates to a quotation with the same structure as <@ Console.Out.WriteLine("Hello World") @>. Builds an expression that represents a call to an static method or module-bound function The MethodInfo describing the method to call. The list of arguments to the method. The resulting expression. open System open FSharp.Quotations open FSharp.Quotations.Patterns let methInfo = match <@ Console.WriteLine("1") @> with | Call(_, mi, _) -> mi | _ -> failwith "call expected" let argExpr = <@ "Hello World" @> Expr.Call(methInfo, [argExpr]) Evaluates to a quotation with the same structure as <@ Console.WriteLine("Hello World") @>. Builds an expression that represents the application of a first class function value to multiple arguments The function to apply. The list of lists of arguments to the function. The resulting expression. open FSharp.Quotations let funcExpr = <@ (fun (x, y) z -> x + y + z) @> let curriedArgExprs = [[ <@ 1 @>; <@ 2 @> ]; [ <@ 3 @> ]] Expr.Applications(funcExpr, curriedArgExprs) Evaluates to a quotation with the same structure as <@ (fun (x, y) z -> x + y + z) (1,2) 3 @>. Builds an expression that represents the application of a first class function value to a single argument. The function to apply. The argument to the function. The resulting expression. open FSharp.Quotations let funcExpr = <@ (fun x -> x + 1) @> let argExpr = <@ 3 @> Expr.Application(funcExpr, argExpr) Evaluates to a quotation with the same structure as <@ (fun x -> x + 1) 3 @>. Builds an expression that represents setting the value held at a particular address. The target expression. The value to set at the address. The resulting expression. open FSharp.Quotations let array = [| 1; 2; 3 |] let addrExpr = Expr.AddressOf(<@ array.[1] @>) Expr.AddressSet(addrExpr, <@ 4 @>) Evaluates to AddressSet (AddressOf (Call (None, GetArray, [PropertyGet (None, array, []), Value (1)])), Value (4)). Builds an expression that represents getting the address of a value. The target expression. The resulting expression. open FSharp.Quotations let array = [| 1; 2; 3 |] Expr.AddressOf(<@ array.[1] @>) Evaluates to AddressOf (Call (None, GetArray, [PropertyGet (None, array, []), Value (1)])). Quoted expressions annotated with System.Type values. The type associated with the variable open FSharp.Quotations open FSharp.Quotations.Patterns match <@ fun v -> v @> with | Lambda(v, body) -> v.Type | _ -> failwith "unreachable" Evaluates to typeof<int> The declared name of the variable open FSharp.Quotations open FSharp.Quotations.Patterns match <@ fun v -> v @> with | Lambda(v, body) -> v.Name | _ -> failwith "unreachable" Evaluates to "v" Indicates if the variable represents a mutable storage location open FSharp.Quotations open FSharp.Quotations.Patterns match <@ fun v -> v @> with | Lambda(v, body) -> v.IsMutable | _ -> failwith "unreachable" Evaluates to false. Fetches or create a new variable with the given name and type from a global pool of shared variables indexed by name and type The name of the variable. The type associated with the variable. The retrieved or created variable. open FSharp.Quotations open FSharp.Quotations.Patterns let valueVar1 = Var.Global("value", typeof<int>) let valueVar2 = Var.Global("value", typeof<int>) Evaluates both to valueVar1 and valueVar2 to the same variable from a global pool of shared variables. Creates a new variable with the given name, type and mutability The declared name of the variable. The type associated with the variable. Indicates if the variable represents a mutable storage location. Default is false. The created variable. open FSharp.Quotations open FSharp.Quotations.Patterns let valueVar = Var("value"), typeof<int>) Evaluates to a new quotation variable with the given name and type. Information at the binding site of a variable Library functionality for F# quotations. See also F# Code Quotations in the F# Language Guide. Re-build combination expressions. The first parameter should be an object returned by the ShapeCombination case of the active pattern in this module. The input shape. The list of arguments. The rebuilt expression. An active pattern that performs a complete decomposition viewing the expression tree as a binding structure The input expression. The decomposed Var, Lambda, or ConstApp. Active patterns for traversing, visiting, rebuilding and transforming expressions in a generic way An active pattern to recognize property setters that have an associated ReflectedDefinition The description of the property. The expression of the method definition if found, or None. open FSharp.Quotations open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns [<ReflectedDefinition>] type C<'T>() = member x.Count with set (v: int) = () let inpExpr = <@ C<int>().Count <- 3 @> let implExpr = match inpExpr with | PropertySet(Some _, PropertySetterWithReflectedDefinition implExpr, [], _valueExpr) -> implExpr | _ -> failwith "unexpected" Evaluates implExpr to a quotation with the same structure as <@ fun (x: C<int>) (v: int) -> () @>, which is the implementation of the setter for the property Count. Note that the correct generic instantiation has been applied to the implementation to reflect the type at the callsite. An active pattern to recognize property getters or values in modules that have an associated ReflectedDefinition The description of the property. The expression of the method definition if found, or None. open FSharp.Quotations open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns [<ReflectedDefinition>] type C<'T>() = member x.Identity = x let inpExpr = <@ C<int>().Identity @> let implExpr = match inpExpr with | PropertyGet(Some _, PropertyGetterWithReflectedDefinition implExpr, [ ]) -> implExpr | _ -> failwith "unexpected" Evaluates implExpr to a quotation with the same structure as <@ fun (x: C<int>) () -> x @>, which is the implementation of the property Identity. Note that the correct generic instantiation has been applied to the implementation to reflect the type at the callsite. An active pattern to recognize methods that have an associated ReflectedDefinition The description of the method. The expression of the method definition if found, or None. open FSharp.Quotations open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns [<ReflectedDefinition>] let f x = (x, x) let inpExpr = <@ f 4 @> let implExpr = match inpExpr with | Call(None, MethodWithReflectedDefinition implExpr, [ _argExpr ]) -> implExpr | _ -> failwith "unexpected" Evaluates implExpr to a quotation with the same structure as <@ fun (x: int) -> (x, x) @>, which is the implementation of the method f. Note that the correct generic instantiation has been applied to the implementation to reflect the type at the callsite. A parameterized active pattern to recognize calls to a specified function or method. The returned elements are the optional target object (present if the target is an instance method), the generic type instantiation (non-empty if the target is a generic instantiation), and the arguments to the function or method. The input template expression to specify the method to call. The optional target object (present if the target is an instance method), the generic type instantiation (non-empty if the target is a generic instantiation), and the arguments to the function or method. Match a specific call to Console.WriteLine taking one string argument: open FSharp.Quotations open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns let inpExpr = <@ Console.WriteLine("hello") @> match inpExpr with | SpecificCall <@ Console.WriteLine("1") @> (None, [], [ argExpr ]) -> argExpr | _ -> failwith "unexpected" Evaluates to a quotation with the same structure as <@ "hello" @>. Calls to this active pattern can be partially applied to pre-evaluate some aspects of the matching. For example: open FSharp.Quotations open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns let (|ConsoleWriteLineOneArg|_|) = (|SpecificCall|_|) <@ Console.WriteLine("1") @> let inpExpr = <@ Console.WriteLine("hello") @> match inpExpr with | ConsoleWriteLineOneArg (None, [], [ argExpr ]) -> argExpr | _ -> failwith "unexpected" Evaluates to a quotation with the same structure as <@ "hello" @>. An active pattern to recognize constant decimal expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8.0M @> with | Decimal v -> v | _ -> failwith "unexpected" Evaluates to 8.0M. An active pattern to recognize constant unsigned int64 expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8UL @> with | UInt64 v -> v | _ -> failwith "unexpected" Evaluates to 8UL. An active pattern to recognize constant int64 expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8L @> with | Int64 v -> v | _ -> failwith "unexpected" Evaluates to 8L. An active pattern to recognize constant unsigned int32 expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8u @> with | UInt32 v -> v | _ -> failwith "unexpected" Evaluates to 8u. An active pattern to recognize constant int32 expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8 @> with | Int32 v -> v | _ -> failwith "unexpected" Evaluates to 8. An active pattern to recognize constant unsigned int16 expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8us @> with | UInt16 v -> v | _ -> failwith "unexpected" Evaluates to 8us. An active pattern to recognize constant int16 expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8s @> with | Int16 v -> v | _ -> failwith "unexpected" Evaluates to 8s. An active pattern to recognize constant byte expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8uy @> with | Byte v -> v | _ -> failwith "unexpected" Evaluates to 8uy. An active pattern to recognize constant signed byte expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 8y @> with | SByte v -> v | _ -> failwith "unexpected" Evaluates to 8y. An active pattern to recognize constant unicode character expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 'a' @> with | Char v -> v | _ -> failwith "unexpected" Evaluates to 'a'. An active pattern to recognize constant 64-bit floating point number expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 1.0 @> with | Double v -> v | _ -> failwith "unexpected" Evaluates to 1.0. An active pattern to recognize constant 32-bit floating point number expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ 1.0f @> with | Single v -> v | _ -> failwith "unexpected" Evaluates to 1.0f. An active pattern to recognize constant string expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ "a" @> with | String v -> v | _ -> failwith "unexpected" Evaluates to "a". An active pattern to recognize constant boolean expressions The input expression to match against. When successful, the pattern binds the constant value from the input expression open FSharp.Quotations.DerivedPatterns match <@ true @> with | Bool v -> v | _ -> failwith "unexpected" Evaluates to true. An active pattern to recognize () constant expressions The input expression to match against. When successful, the pattern does not bind any results open FSharp.Quotations.DerivedPatterns match <@ () @> with | Unit v -> v | _ -> failwith "unexpected" Evaluates to true. An active pattern to recognize expressions of the form a || b The input expression to match against. When successful, the pattern binds the left and right parts of the input expression open FSharp.Quotations.DerivedPatterns match <@ true || false @> with | OrElse (a, b) -> (a, b) | _ -> failwith "unexpected" Evaluates to <@ true @>, <@ false @>. An active pattern to recognize expressions of the form a && b The input expression to match against. When successful, the pattern binds the left and right parts of the input expression open FSharp.Quotations.DerivedPatterns match <@ true && false @> with | AndAlso (a, b) -> (a, b) | _ -> failwith "unexpected" Evaluates to <@ true @>, <@ false @>. An active pattern to recognize expressions that represent the application of a (possibly curried or tupled) first class function value The input expression to match against. When successful, the pattern binds the function and curried arguments of the input expression open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns match <@ (fun f -> f (1, 2) 3) @> with | Lambda(_, Applications (f, curriedArgs)) -> curriedArgs |> List.map (fun args -> args.Length) | _ -> failwith "unexpected" Evaluates to [2; 1]. An active pattern to recognize expressions that represent a (possibly curried or tupled) first class function value The input expression to match against. When successful, the pattern binds the curried variables and body of the input expression open FSharp.Quotations.Patterns open FSharp.Quotations.DerivedPatterns match <@ (fun (a1, a2) b -> ()) @> with | Lambdas(curriedVars, _) -> curriedVars |> List.map (List.map (fun arg -> arg.Name)) | _ -> failwith "unexpected" Evaluates to [["a1"; "a2"]; ["b"]]. Contains a set of derived F# active patterns to analyze F# expression objects An active pattern to recognize expressions that represent setting a mutable variable The input expression to match against. When successful, the pattern binds the variable and value expression of the input expression An active pattern to recognize expressions that represent a variable The input expression to match against. When successful, the pattern binds the variable of the input expression An active pattern to recognize expressions that are a value with an associated definition The input expression to match against. When successful, the pattern binds the boxed value, its static type and its definition An active pattern to recognize expressions that represent a constant value The input expression to match against. When successful, the pattern binds the boxed value, its static type and its name An active pattern to recognize expressions that represent a constant value. This also matches expressions matched by ValueWithName. The input expression to match against. When successful, the pattern binds the boxed value and its static type An active pattern to recognize expressions that represent a test if a value is of a particular union case The input expression to match against. When successful, the pattern binds the expression and union case being tested An active pattern to recognize expressions that represent a dynamic type test The input expression to match against. When successful, the pattern binds the expression and type being tested An active pattern to recognize expressions that represent getting a tuple field The input expression to match against. When successful, the pattern binds the expression and tuple field being accessed An active pattern to recognize expressions that represent a try/finally construct The input expression to match against. When successful, the pattern binds the body and handler parts of the try/finally expression An active pattern to recognize expressions that represent a try/with construct for exception filtering and catching The input expression to match against. When successful, the pattern binds the body, exception variable, filter expression and catch expression of the input expression An active pattern to recognize expressions that represent sequential execution of one expression followed by another The input expression to match against. When successful, the pattern binds the two sub-expressions of the input expression An active pattern to recognize expressions that represent a nested typed quotation literal The input expression to match against. When successful, the pattern binds the nested quotation expression of the input expression An active pattern to recognize expressions that represent a nested raw quotation literal The input expression to match against. When successful, the pattern binds the nested quotation expression of the input expression An active pattern to recognize expressions that represent a nested quotation literal The input expression to match against. When successful, the pattern binds the nested quotation expression of the input expression An active pattern to recognize expressions that represent setting a static or instance property, or a non-function value declared in a module The input expression to match against. When successful, the pattern binds the object, property, indexer arguments and setter value of the input expression An active pattern to recognize expressions that represent the read of a static or instance property, or a non-function value declared in a module The input expression to match against. When successful, the pattern binds the object, property and indexer arguments of the input expression An active pattern to recognize expressions that represent construction of struct tuple values The input expression to match against. When successful, the pattern binds the element expressions of the input expression An active pattern to recognize expressions that represent construction of tuple values The input expression to match against. When successful, the pattern binds the element expressions of the input expression An active pattern to recognize expressions that represent construction of particular union case values The input expression to match against. When successful, the pattern binds the union case and field values of the input expression An active pattern to recognize expressions that represent construction of record values The input expression to match against. When successful, the pattern binds the record type and field values of the input expression An active pattern to recognize expressions that represent invocation of object constructors The input expression to match against. When successful, the pattern binds the constructor and arguments of the input expression An active pattern to recognize expressions that represent construction of delegate values The input expression to match against. When successful, the pattern binds the delegate type, argument parameters and body of the input expression An active pattern to recognize expressions that represent invocations of a default constructor of a struct The input expression to match against. When successful, the pattern binds the relevant type of the input expression An active pattern to recognize expressions that represent the construction of arrays The input expression to match against. When successful, the pattern binds the element type and values of the input expression An active pattern to recognize expressions that represent recursive let bindings of one or more variables The input expression to match against. When successful, the pattern binds the bindings and body of the input expression An active pattern to recognize expressions that represent let bindings The input expression to match against. When successful, the pattern binds the variable, binding expression and body of the input expression An active pattern to recognize expressions that represent first class function values The input expression to match against. When successful, the pattern binds the variable and body of the input expression An active pattern to recognize expressions that represent conditionals The input expression to match against. When successful, the pattern binds the condition, then-branch and else-branch of the input expression An active pattern to recognize expressions that represent while loops The input expression to match against. When successful, the pattern binds the guard and body of the input expression An active pattern to recognize expressions that represent loops over integer ranges The input expression to match against. When successful, the pattern binds the value, start, finish and body of the input expression An active pattern to recognize expressions that represent setting a static or instance field The input expression to match against. When successful, the pattern binds the object, field and value of the input expression An active pattern to recognize expressions that represent getting a static or instance field The input expression to match against. When successful, the pattern binds the object and field of the input expression An active pattern to recognize expressions that represent coercions from one type to another The input expression to match against. When successful, the pattern binds the source expression and target type of the input expression An active pattern to recognize expressions that represent calls to static and instance methods, and functions defined in modules, including witness arguments The input expression to match against. When successful, the pattern binds the object, method, witness-argument and argument sub-expressions of the input expression An active pattern to recognize expressions that represent calls to static and instance methods, and functions defined in modules The input expression to match against. When successful, the pattern binds the object, method and argument sub-expressions of the input expression An active pattern to recognize expressions that represent applications of first class function values The input expression to match against. When successful, the pattern binds the function and argument of the input expression An active pattern to recognize expressions that represent setting the value held at an address The input expression to match against. When successful, the pattern binds the target and value expressions of the input expression An active pattern to recognize expressions that represent getting the address of a value The input expression to match against. When successful, the pattern binds the sub-expression of the input AddressOf expression Contains a set of primitive F# active patterns to analyze F# expression objects Copies a block of memory to a specified destination address starting from a specified source address until a specified byte count of (count * sizeof<'T>). The destination pointer. The source pointer. The source pointer. Copies a value to a specified destination address from a specified source address. The destination pointer. The source pointer. Initializes a specified block of memory starting at a specific address to a given byte count and initial byte value. The input pointer. The initial byte value. The total repeat count of the byte value. Clears the value stored at the location of a given native pointer. The input pointer. Tests whether the given native pointer is null. The input pointer. Whether the given native pointer is null. Gets the null native pointer. The null native pointer. Allocates a region of memory on the stack. The number of objects of type T to allocate. A typed pointer to the allocated memory. Assigns the value into the memory location referenced by the typed native pointer computed by adding index * sizeof<'T> to the given input pointer. The input pointer. The index by which to offset the pointer. The value to assign. Assigns the value into the memory location referenced by the given typed native pointer. The input pointer. The value to assign. Dereferences the given typed native pointer. The input pointer. The value at the pointer address. Dereferences the typed native pointer computed by adding index * sizeof<'T> to the given input pointer. The input pointer. The index by which to offset the pointer. The value at the pointer address. Returns a typed native pointer by adding index * sizeof<'T> to the given input pointer. The input pointer. The index by which to offset the pointer. A typed pointer. Converts a given typed native pointer to a managed pointer. The typed native pointer. The managed pointer. Returns a Common IL (Intermediate Language) signature pointer for a given typed native pointer. The typed native pointer. A Common IL signature pointer. Returns a typed native pointer for a Common IL (Intermediate Language) signature pointer. The Common IL signature pointer. A typed native pointer. Returns an untyped native pointer for a given typed native pointer. The typed native pointer. An untyped native pointer. Returns a typed native pointer for a untyped native pointer. The untyped native pointer. A typed native pointer. Returns a machine address for a given typed native pointer. The typed native pointer. The machine address. Returns a typed native pointer for a given machine address. The machine address. A typed native pointer. Contains operations on native pointers. Use of these operators may result in the generation of unverifiable code. Library functionality for native interoperability. See also F# External Functions in the F# Language Guide. First-class listening points (i.e. objects that permit you to register a callback activated when the event is triggered). Events and Observables A delegate type associated with the F# event type IEvent<_> The object that fired the event. The event arguments. Events and Observables First class event values for CLI events conforming to CLI Framework standards. Events and Observables Remove a listener delegate from an event listener store. The delegate to be removed from the event listener store. Connect a handler delegate object to the event. A handler can be later removed using RemoveHandler. The listener will be invoked when the event is fired. A delegate to be invoked when the event is fired. First class event values for arbitrary delegate types. F# gives special status to member properties compatible with type IDelegateEvent and tagged with the CLIEventAttribute. In this case the F# compiler generates appropriate CLI metadata to make the member appear to other CLI languages as a CLI event. Events and Observables The type of delayed computations. Use the values in the Lazy module to manipulate values of this type, and the notation lazy expr to create values of type . Lazy Computation Publishes the event as a first class value. Triggers the event using the given parameters. The event parameters. Creates an observable object. The created event. Event implementations for the IEvent<_> type. Events and Observables Publishes the event as a first class event value. Triggers the event using the given sender object and parameters. The sender object may be null. The object triggering the event. The parameters for the event. Creates an event object suitable for delegate types following the standard .NET Framework convention of a first 'sender' argument. The created event. Event implementations for a delegate types following the standard .NET Framework convention of a first 'sender' argument. Events and Observables Publishes the event as a first class event value. Triggers the event using the given parameters. The parameters for the event. Creates an event object suitable for implementing an arbitrary type of delegate. The event object. Event implementations for an arbitrary type of delegate. Events and Observables Creates an asynchronous computation that just returns (). A cancellation check is performed when the computation is executed. The existence of this method permits the use of empty else branches in the async { ... } computation expression syntax. An asynchronous computation that returns (). Creates an asynchronous computation that runs computation repeatedly until guard() becomes false. A cancellation check is performed whenever the computation is executed. The existence of this method permits the use of while in the async { ... } computation expression syntax. The function to determine when to stop executing computation. The function to be executed. Equivalent to the body of a while expression. An asynchronous computation that behaves similarly to a while loop when run. Creates an asynchronous computation that runs binder(resource). The action resource.Dispose() is executed as this computation yields its result or if the asynchronous computation exits by an exception or by cancellation. A cancellation check is performed when the computation is executed. The existence of this method permits the use of use and use! in the async { ... } computation expression syntax. The resource to be used and disposed. The function that takes the resource and returns an asynchronous computation. An asynchronous computation that binds and eventually disposes resource. Creates an asynchronous computation that runs computation and returns its result. If an exception happens then catchHandler(exn) is called and the resulting computation executed instead. A cancellation check is performed when the computation is executed. The existence of this method permits the use of try/with in the async { ... } computation expression syntax. The input computation. The function to run when computation throws an exception. An asynchronous computation that executes computation and calls catchHandler if an exception is thrown. Creates an asynchronous computation that runs computation. The action compensation is executed after computation completes, whether computation exits normally or by an exception. If compensation raises an exception itself the original exception is discarded and the new exception becomes the overall result of the computation. A cancellation check is performed when the computation is executed. The existence of this method permits the use of try/finally in the async { ... } computation expression syntax. The input computation. The action to be run after computation completes or raises an exception (including cancellation). An asynchronous computation that executes computation and compensation afterwards or when an exception is raised. Delegates to the input computation. The existence of this method permits the use of return! in the async { ... } computation expression syntax. The input computation. The input computation. Creates an asynchronous computation that returns the result v. A cancellation check is performed when the computation is executed. The existence of this method permits the use of return in the async { ... } computation expression syntax. The value to return from the computation. An asynchronous computation that returns value when executed. Creates an asynchronous computation that enumerates the sequence seq on demand and runs body for each element. A cancellation check is performed on each iteration of the loop. The existence of this method permits the use of for in the async { ... } computation expression syntax. The sequence to enumerate. A function to take an item from the sequence and create an asynchronous computation. Can be seen as the body of the for expression. An asynchronous computation that will enumerate the sequence and run body for each element. Creates an asynchronous computation that runs generator. A cancellation check is performed when the computation is executed. The function to run. An asynchronous computation that runs generator. Creates an asynchronous computation that first runs computation1 and then runs computation2, returning the result of computation2. A cancellation check is performed when the computation is executed. The existence of this method permits the use of expression sequencing in the async { ... } computation expression syntax. The first part of the sequenced computation. The second part of the sequenced computation. An asynchronous computation that runs both of the computations sequentially. Creates an asynchronous computation that runs computation, and when computation generates a result T, runs binder res. A cancellation check is performed when the computation is executed. The existence of this method permits the use of let! in the async { ... } computation expression syntax. The computation to provide an unbound result. The function to bind the result of computation. An asynchronous computation that performs a monadic bind on the result of computation. Generate an object used to build asynchronous computations using F# computation expressions. The value 'async' is a pre-defined instance of this type. A cancellation check is performed when the computation is executed. The type of the async operator, used to build workflows for asynchronous computations. Async Programming The F# compiler emits calls to this function to implement F# async expressions. A value indicating asynchronous execution. The F# compiler emits calls to this function to implement F# async expressions. A value indicating asynchronous execution. Used by MailboxProcessor The F# compiler emits calls to this function to implement F# async expressions. A value indicating asynchronous execution. The F# compiler emits calls to this function to implement F# async expressions. The F# compiler emits calls to this function to implement F# async expressions. A value indicating asynchronous execution. Used by MailboxProcessor The F# compiler emits references to this type to implement F# async expressions. Async Internals The F# compiler emits references to this type to implement F# async expressions. Async Internals Gets the default cancellation token for executing asynchronous computations. The default CancellationToken. Cancellation and Exceptions Async.DefaultCancellationToken.Register(fun () -> printfn "Computation Cancelled") |> ignore let primes = [ 2; 3; 5; 7; 11 ] for i in primes do async { do! Async.Sleep(i * 1000) printfn $"{i}" } |> Async.Start Thread.Sleep(6000) Async.CancelDefaultToken() printfn "Tasks Finished" This will print "2" 2 seconds from start, "3" 3 seconds from start, "5" 5 seconds from start, cease computation and then print "Computation Cancelled", followed by "Tasks Finished". Creates an asynchronous computation that returns the CancellationToken governing the execution of the computation. In async { let! token = Async.CancellationToken ...} token can be used to initiate other asynchronous operations that will cancel cooperatively with this workflow. An asynchronous computation capable of retrieving the CancellationToken from a computation expression. Cancellation and Exceptions Creates an asynchronous computation that executes computation. If this computation is cancelled before it completes then the computation generated by running compensation is executed. The input asynchronous computation. The function to be run if the computation is cancelled. An asynchronous computation that runs the compensation if the input computation is cancelled. Cancellation and Exceptions let primes = [ 2; 3; 5; 7; 11 ] for i in primes do Async.TryCancelled( async { do! Async.Sleep(i * 1000) printfn $"{i}" }, fun oce -> printfn $"Computation Cancelled: {i}") |> Async.Start Thread.Sleep(6000) Async.CancelDefaultToken() printfn "Tasks Finished" This will print "2" 2 seconds from start, "3" 3 seconds from start, "5" 5 seconds from start, cease computation and then print "Computation Cancelled: 7", "Computation Cancelled: 11" and "Tasks Finished" in any order. Creates an asynchronous computation that queues a work item that runs its continuation. A computation that generates a new work item in the thread pool. Threads and Contexts async { do! Async.SwitchToNewThread() do! someLongRunningComputation() do! Async.SwitchToThreadPool() for i in 1 .. 10 do do! someShortRunningComputation() } |> Async.StartImmediate This will run someLongRunningComputation() without blocking the threads in the threadpool, and then switch to the threadpool for shorter computations. Creates an asynchronous computation that creates a new thread and runs its continuation in that thread. A computation that will execute on a new thread. Threads and Contexts async { do! Async.SwitchToNewThread() do! someLongRunningComputation() } |> Async.StartImmediate This will run someLongRunningComputation() without blocking the threads in the threadpool. Creates an asynchronous computation that runs its continuation using syncContext.Post. If syncContext is null then the asynchronous computation is equivalent to SwitchToThreadPool(). The synchronization context to accept the posted computation. An asynchronous computation that uses the syncContext context to execute. Threads and Contexts Runs an asynchronous computation, starting immediately on the current operating system thread. Call one of the three continuations when the operation completes. If no cancellation token is provided then the default cancellation token is used. The asynchronous computation to execute. The function called on success. The function called on exception. The function called on cancellation. The CancellationToken to associate with the computation. The default is used if this parameter is not provided. Starting Async Computations Runs an asynchronous computation, starting immediately on the current operating system thread, but also returns the execution as If no cancellation token is provided then the default cancellation token is used. You may prefer using this method if you want to achieve a similar behavior to async await in C# as async computation starts on the current thread with an ability to return a result. The asynchronous computation to execute. The CancellationToken to associate with the computation. The default is used if this parameter is not provided. A that will be completed in the corresponding state once the computation terminates (produces the result, throws exception or gets canceled) Starting Async Computations printfn "A" let t = async { printfn "B" do! Async.Sleep(1000) printfn "C" } |> Async.StartImmediateAsTask printfn "D" t.Wait() printfn "E" Prints "A", "B", "D" immediately, then "C", "E" in 1 second. Runs an asynchronous computation, starting immediately on the current operating system thread. If no cancellation token is provided then the default cancellation token is used. The asynchronous computation to execute. The CancellationToken to associate with the computation. The default is used if this parameter is not provided. Starting Async Computations printfn "A" async { printfn "B" do! Async.Sleep(1000) printfn "C" } |> Async.StartImmediate printfn "D" Prints "A", "B", "D" immediately, then "C" in 1 second Creates an asynchronous computation which starts the given computation as a Starting Async Computations Starts a child computation within an asynchronous workflow. This allows multiple asynchronous computations to be executed simultaneously. This method should normally be used as the immediate right-hand-side of a let! binding in an F# asynchronous workflow, that is, async { ... let! completor1 = childComputation1 |> Async.StartChild let! completor2 = childComputation2 |> Async.StartChild ... let! result1 = completor1 let! result2 = completor2 ... } When used in this way, each use of StartChild starts an instance of childComputation and returns a completor object representing a computation to wait for the completion of the operation. When executed, the completor awaits the completion of childComputation. The child computation. The timeout value in milliseconds. If one is not provided then the default value of -1 corresponding to . A new computation that waits for the input computation to finish. Cancellation and Exceptions let computeWithTimeout timeout = async { let! completor1 = Async.StartChild( (async { do! Async.Sleep(1000) return 1 }), millisecondsTimeout = timeout) let! completor2 = Async.StartChild( (async { do! Async.Sleep(2000) return 2 }), millisecondsTimeout = timeout) let! v1 = completor1 let! v2 = completor2 printfn $"Result: {v1 + v2}" } |> Async.RunSynchronously Will throw a System.TimeoutException if called with a timeout less than 2000, otherwise will print "Result: 3". Executes a computation in the thread pool. If no cancellation token is provided then the default cancellation token is used. A that will be completed in the corresponding state once the computation terminates (produces the result, throws exception or gets canceled) Starting Async Computations printfn "A" let t = async { printfn "B" do! Async.Sleep(1000) printfn "C" } |> Async.StartAsTask printfn "D" t.Wait() printfn "E" Prints "A", then "D", "B" quickly in any order, then "C", "E" in 1 second. Starts the asynchronous computation in the thread pool. Do not await its result. If no cancellation token is provided then the default cancellation token is used. The computation to run asynchronously. The cancellation token to be associated with the computation. If one is not supplied, the default cancellation token is used. Starting Async Computations printfn "A" async { printfn "B" do! Async.Sleep(1000) printfn "C" } |> Async.Start printfn "D" Prints "A", then "D", "B" quickly in any order, and then "C" in 1 second. Creates an asynchronous computation that will sleep for the given time. This is scheduled using a System.Threading.Timer object. The operation will not block operating system threads for the duration of the wait. The amount of time to sleep. An asynchronous computation that will sleep for the given time. Thrown when the due time is negative. Awaiting Results async { printfn "A" do! Async.Sleep(TimeSpan(0, 0, 1)) printfn "B" } |> Async.Start printfn "C" Prints "C", then "A" quickly, and then "B" 1 second later. Creates an asynchronous computation that will sleep for the given time. This is scheduled using a System.Threading.Timer object. The operation will not block operating system threads for the duration of the wait. The number of milliseconds to sleep. An asynchronous computation that will sleep for the given time. Thrown when the due time is negative and not infinite. Awaiting Results async { printfn "A" do! Async.Sleep(1000) printfn "B" } |> Async.Start printfn "C" Prints "C" and "A" quickly in any order, and then "B" 1 second later Creates an asynchronous computation that executes all the given asynchronous computations sequentially. If all child computations succeed, an array of results is passed to the success continuation. If any child computation raises an exception, then the overall computation will trigger an exception, and cancel the others. The overall computation will respond to cancellation while executing the child computations. If cancelled, the computation will cancel any remaining child computations but will still wait for the other child computations to complete. A sequence of distinct computations to be run in sequence. A computation that returns an array of values from the sequence of input computations. Composing Async Computations let primes = [ 2; 3; 5; 7; 10; 11 ] let computations = [ for i in primes do async { do! Async.Sleep(System.Random().Next(1000, 2000)) if i % 2 > 0 then printfn $"{i}" return true else return false } ] let t = Async.Sequential(computations) |> Async.StartAsTask t.Wait() printfn $"%A{t.Result}" This will print "3", "5", "7", "11" with ~1-2 seconds between them except for pauses where even numbers would be and then prints [| false; true; true; true; false; true |]. Runs the asynchronous computation and await its result. If an exception occurs in the asynchronous computation then an exception is re-raised by this function. If no cancellation token is provided then the default cancellation token is used. The computation is started on the current thread if is null, has of true, and no timeout is specified. Otherwise the computation is started by queueing a new work item in the thread pool, and the current thread is blocked awaiting the completion of the computation. The timeout parameter is given in milliseconds. A value of -1 is equivalent to . The computation to run. The amount of time in milliseconds to wait for the result of the computation before raising a . If no value is provided for timeout then a default of -1 is used to correspond to . The cancellation token to be associated with the computation. If one is not supplied, the default cancellation token is used. The result of the computation. Starting Async Computations printfn "A" let result = async { printfn "B" do! Async.Sleep(1000) printfn "C" 17 } |> Async.RunSynchronously printfn "D" Prints "A", "B" immediately, then "C", "D" in 1 second. result is set to 17. Creates an asynchronous computation that executes all the given asynchronous computations, initially queueing each as work items and using a fork/join pattern. If all child computations succeed, an array of results is passed to the success continuation. If any child computation raises an exception, then the overall computation will trigger an exception, and cancel the others. The overall computation will respond to cancellation while executing the child computations. If cancelled, the computation will cancel any remaining child computations but will still wait for the other child computations to complete. A sequence of distinct computations to be parallelized. The maximum degree of parallelism in the parallel execution. A computation that returns an array of values from the sequence of input computations. Composing Async Computations let primes = [ 2; 3; 5; 7; 10; 11 ] let computations = [ for i in primes do async { do! Async.Sleep(System.Random().Next(1000, 2000)) return if i % 2 > 0 then printfn $"{i}" true else false } ] let t = Async.Parallel(computations, maxDegreeOfParallelism=3) |> Async.StartAsTask t.Wait() printfn $"%A{t.Result}" This will print "3", "5" (in any order) in 1-2 seconds, and then "7", "11" (in any order) in 1-2 more seconds and then [| false; true; true; true; false; true |]. Creates an asynchronous computation that executes all the given asynchronous computations, initially queueing each as work items and using a fork/join pattern. If all child computations succeed, an array of results is passed to the success continuation. If any child computation raises an exception, then the overall computation will trigger an exception, and cancel the others. The overall computation will respond to cancellation while executing the child computations. If cancelled, the computation will cancel any remaining child computations but will still wait for the other child computations to complete. A sequence of distinct computations to be parallelized. A computation that returns an array of values from the sequence of input computations. Composing Async Computations let primes = [ 2; 3; 5; 7; 10; 11 ] let t = [ for i in primes do async { do! Async.Sleep(System.Random().Next(1000, 2000)) if i % 2 > 0 then printfn $"{i}" return true else return false } ] |> Async.Parallel |> Async.StartAsTask t.Wait() printfn $"%A{t.Result}" This will print "3", "5", "7", "11" (in any order) in 1-2 seconds and then [| false; true; true; true; false; true |]. Generates a scoped, cooperative cancellation handler for use within an asynchronous workflow. For example, async { use! holder = Async.OnCancel interruption ... } generates an asynchronous computation where, if a cancellation happens any time during the execution of the asynchronous computation in the scope of holder, then action interruption is executed on the thread that is performing the cancellation. This can be used to arrange for a computation to be asynchronously notified that a cancellation has occurred, e.g. by setting a flag, or deregistering a pending I/O action. The function that is executed on the thread performing the cancellation. An asynchronous computation that triggers the interruption if it is cancelled before being disposed. Cancellation and Exceptions let primes = [ 2; 3; 5; 7; 11 ] for i in primes do async { use! holder = Async.OnCancel(fun () -> printfn $"Computation Cancelled: {i}") do! Async.Sleep(i * 1000) printfn $"{i}" } |> Async.Start Thread.Sleep(6000) Async.CancelDefaultToken() printfn "Tasks Finished" This will print "2" 2 seconds from start, "3" 3 seconds from start, "5" 5 seconds from start, cease computation and then print "Computation Cancelled: 7", "Computation Cancelled: 11" and "Tasks Finished" in any order. Creates an asynchronous computation that runs the given computation and ignores its result. The input computation. A computation that is equivalent to the input computation, but disregards the result. Composing Async Computations let readFile filename numBytes = async { use file = System.IO.File.OpenRead(filename) printfn "Reading from file %s." filename // Throw away the data being read. do! file.AsyncRead(numBytes) |> Async.Ignore } readFile "example.txt" 42 |> Async.Start Reads bytes from a given file asynchronously and then ignores the result, allowing the do! to be used with functions that return an unwanted value. Creates an asynchronous computation that captures the current success, exception and cancellation continuations. The callback must eventually call exactly one of the given continuations. The function that accepts the current success, exception, and cancellation continuations. An asynchronous computation that provides the callback with the current continuations. Composing Async Computations let someRiskyBusiness() = match DateTime.Today with | dt when dt.DayOfWeek = DayOfWeek.Monday -> failwith "Not compatible with Mondays" | dt -> dt let computation = (fun (successCont, exceptionCont, cancellationCont) -> try someRiskyBusiness () |> successCont with | :? OperationCanceledException as oce -> cancellationCont oce | e -> exceptionCont e) |> Async.FromContinuations Async.StartWithContinuations( computation, (fun result -> printfn $"Result: {result}"), (fun e -> printfn $"Exception: {e}"), (fun oce -> printfn $"Cancelled: {oce}") ) This anonymous function will call someRiskyBusiness() and properly use the provided continuations defined to report the outcome. Creates an asynchronous computation in terms of a Begin/End pair of actions in the style used in .NET 2.0 APIs. The computation will respond to cancellation while waiting for the completion of the operation. If a cancellation occurs, and cancelAction is specified, then it is executed, and the computation continues to wait for the completion of the operation. If cancelAction is not specified, then cancellation causes the computation to stop immediately, and subsequent invocations of the callback are ignored. The first argument for the operation. The second argument for the operation. The third argument for the operation. The function initiating a traditional CLI asynchronous operation. The function completing a traditional CLI asynchronous operation. An optional function to be executed when a cancellation is requested. An asynchronous computation wrapping the given Begin/End functions. Legacy .NET Async Interoperability Creates an asynchronous computation in terms of a Begin/End pair of actions in the style used in .NET 2.0 APIs. The computation will respond to cancellation while waiting for the completion of the operation. If a cancellation occurs, and cancelAction is specified, then it is executed, and the computation continues to wait for the completion of the operation. If cancelAction is not specified, then cancellation causes the computation to stop immediately, and subsequent invocations of the callback are ignored. The first argument for the operation. The second argument for the operation. The function initiating a traditional CLI asynchronous operation. The function completing a traditional CLI asynchronous operation. An optional function to be executed when a cancellation is requested. An asynchronous computation wrapping the given Begin/End functions. Legacy .NET Async Interoperability Creates an asynchronous computation in terms of a Begin/End pair of actions in the style used in .NET 2.0 APIs. The computation will respond to cancellation while waiting for the completion of the operation. If a cancellation occurs, and cancelAction is specified, then it is executed, and the computation continues to wait for the completion of the operation. If cancelAction is not specified, then cancellation causes the computation to stop immediately, and subsequent invocations of the callback are ignored. The argument for the operation. The function initiating a traditional CLI asynchronous operation. The function completing a traditional CLI asynchronous operation. An optional function to be executed when a cancellation is requested. An asynchronous computation wrapping the given Begin/End functions. Legacy .NET Async Interoperability Creates an asynchronous computation in terms of a Begin/End pair of actions in the style used in CLI APIs. The computation will respond to cancellation while waiting for the completion of the operation. If a cancellation occurs, and cancelAction is specified, then it is executed, and the computation continues to wait for the completion of the operation. If cancelAction is not specified, then cancellation causes the computation to stop immediately, and subsequent invocations of the callback are ignored. The function initiating a traditional CLI asynchronous operation. The function completing a traditional CLI asynchronous operation. An optional function to be executed when a cancellation is requested. An asynchronous computation wrapping the given Begin/End functions. Legacy .NET Async Interoperability Creates an asynchronous computation that executes all given asynchronous computations in parallel, returning the result of the first succeeding computation (one whose result is 'Some x'). If all child computations complete with None, the parent computation also returns None. If any child computation raises an exception, then the overall computation will trigger an exception, and cancel the others. The overall computation will respond to cancellation while executing the child computations. If cancelled, the computation will cancel any remaining child computations but will still wait for the other child computations to complete. A sequence of computations to be parallelized. A computation that returns the first succeeding computation. Composing Async Computations printfn "Starting" let primes = [ 2; 3; 5; 7 ] let computations = [ for i in primes do async { do! Async.Sleep(System.Random().Next(1000, 2000)) return if i % 2 > 0 then Some(i) else None } ] computations |> Async.Choice |> Async.RunSynchronously |> function | Some (i) -> printfn $"{i}" | None -> printfn "No Result" Prints one randomly selected odd number in 1-2 seconds. If the list is changed to all even numbers, it will instead print "No Result". let primes = [ 2; 3; 5; 7 ] let computations = [ for i in primes do async { do! Async.Sleep(System.Random().Next(1000, 2000)) return if i % 2 > 0 then Some(i) else failwith $"Even numbers not supported: {i}" } ] computations |> Async.Choice |> Async.RunSynchronously |> function | Some (i) -> printfn $"{i}" | None -> printfn "No Result" Will sometimes print one randomly selected odd number, sometimes throw System.Exception("Even numbers not supported: 2"). Creates an asynchronous computation that executes computation. If this computation completes successfully then return Choice1Of2 with the returned value. If this computation raises an exception before it completes then return Choice2Of2 with the raised exception. The input computation that returns the type T. A computation that returns a choice of type T or exception. Cancellation and Exceptions let someRiskyBusiness() = match DateTime.Today with | dt when dt.DayOfWeek = DayOfWeek.Monday -> failwith "Not compatible with Mondays" | dt -> dt async { return someRiskyBusiness() } |> Async.Catch |> Async.RunSynchronously |> function | Choice1Of2 result -> printfn $"Result: {result}" | Choice2Of2 e -> printfn $"Exception: {e}" Prints the returned value of someRiskyBusiness() or the exception if there is one. Raises the cancellation condition for the most recent set of asynchronous computations started without any specific CancellationToken. Replaces the global CancellationTokenSource with a new global token source for any asynchronous computations created after this point without any specific CancellationToken. Cancellation and Exceptions let primes = [ 2; 3; 5; 7; 11 ] let computations = [ for i in primes do async { do! Async.Sleep(i * 1000) printfn $"{i}" } ] try let t = Async.Parallel(computations, 3) |> Async.StartAsTask Thread.Sleep(6000) Async.CancelDefaultToken() printfn $"Tasks Finished: %A{t.Result}" with | :? System.AggregateException as ae -> printfn $"Tasks Not Finished: {ae.Message}" This will print "2" 2 seconds from start, "3" 3 seconds from start, "5" 5 seconds from start, cease computation and then print "Tasks Not Finished: One or more errors occurred. (A task was canceled.)". Creates an asynchronous computation that will wait on the given WaitHandle. The computation returns true if the handle indicated a result within the given timeout. The WaitHandle that can be signalled. The timeout value in milliseconds. If one is not provided then the default value of -1 corresponding to . An asynchronous computation that waits on the given WaitHandle. Awaiting Results Return an asynchronous computation that will wait for the given task to complete and return its result. The task to await. If an exception occurs in the asynchronous computation then an exception is re-raised by this function. If the task is cancelled then is raised. Note that the task may be governed by a different cancellation token to the overall async computation where the AwaitTask occurs. In practice you should normally start the task with the cancellation token returned by let! ct = Async.CancellationToken, and catch any at the point where the overall async is started. Awaiting Results Return an asynchronous computation that will wait for the given task to complete and return its result. The task to await. If an exception occurs in the asynchronous computation then an exception is re-raised by this function. If the task is cancelled then is raised. Note that the task may be governed by a different cancellation token to the overall async computation where the AwaitTask occurs. In practice you should normally start the task with the cancellation token returned by let! ct = Async.CancellationToken, and catch any at the point where the overall async is started. Awaiting Results Creates an asynchronous computation that will wait on the IAsyncResult. The computation returns true if the handle indicated a result within the given timeout. The IAsyncResult to wait on. The timeout value in milliseconds. If one is not provided then the default value of -1 corresponding to . An asynchronous computation that waits on the given IAsyncResult. Awaiting Results Creates an asynchronous computation that waits for a single invocation of a CLI event by adding a handler to the event. Once the computation completes or is cancelled, the handler is removed from the event. The computation will respond to cancellation while waiting for the event. If a cancellation occurs, and cancelAction is specified, then it is executed, and the computation continues to wait for the event. If cancelAction is not specified, then cancellation causes the computation to cancel immediately. The event to handle once. An optional function to execute instead of cancelling when a cancellation is issued. An asynchronous computation that waits for the event to be invoked. Awaiting Results Creates three functions that can be used to implement the .NET 1.0 Asynchronous Programming Model (APM) for a given asynchronous computation. A function generating the asynchronous computation to split into the traditional .NET Asynchronous Programming Model. A tuple of the begin, end, and cancel members. Legacy .NET Async Interoperability Holds static members for creating and manipulating asynchronous computations. See also F# Language Guide - Async Workflows. Async Programming An asynchronous computation, which, when run, will eventually produce a value of type T, or else raises an exception. This type has no members. Asynchronous computations are normally specified either by using an async expression or the static methods in the type. See also F# Language Guide - Async Workflows. Library functionality for asynchronous programming, events and agents. See also Asynchronous Programming, Events and Lazy Expressions in the F# Language Guide. Async Programming The entry point for the dynamic implementation of the corresponding operation. Do not use directly, only used when executing quotations that involve tasks or other reflective execution of F# code. Hosts the task code in a state machine and starts the task, executing in the threadpool using Task.Run Contains methods to build tasks using the F# computation expression syntax The entry point for the dynamic implementation of the corresponding operation. Do not use directly, only used when executing quotations that involve tasks or other reflective execution of F# code. Hosts the task code in a state machine and starts the task. Contains methods to build tasks using the F# computation expression syntax Specifies a unit of task code which produces no result Specifies the iterative execution of a unit of task code. Specifies a unit of task code which executed using try/with semantics Specifies a unit of task code which executed using try/finally semantics Specifies a unit of task code which returns a value Specifies the iterative execution of a unit of task code. Specifies the delayed execution of a unit of task code. Specifies the sequential composition of two units of task code. Contains methods to build tasks using the F# computation expression syntax A special compiler-recognised delegate type for specifying blocks of task code with access to the state machine. Represents the runtime continuation of a task state machine created dynamically This is used by the compiler as a template for creating state machine structs Holds the MethodBuilder for the state machine Holds the final result of the state machine The extra data stored in ResumableStateMachine for tasks Raises a timeout exception if a message not received in this amount of time. By default no timeout is used. Occurs when the execution of the agent results in an exception. Occurs when the execution of the agent results in an exception. Raises a timeout exception if a message not received in this amount of time. By default no timeout is used. Returns the number of unprocessed messages in the message queue of the agent. Occurs when the execution of the agent results in an exception. Scans for a message by looking through messages in arrival order until scanner returns a Some value. Other messages remain in the queue. This method is for use within the body of the agent. For each agent, at most one concurrent reader may be active, so no more than one concurrent call to Receive, TryReceive, Scan and/or TryScan may be active. The function to return None if the message is to be skipped or Some if the message is to be processed and removed from the queue. An optional timeout in milliseconds. Defaults to -1 which corresponds to . An asynchronous computation that scanner built off the read message. Waits for a message. This will consume the first message in arrival order. This method is for use within the body of the agent. Returns None if a timeout is given and the timeout is exceeded. This method is for use within the body of the agent. For each agent, at most one concurrent reader may be active, so no more than one concurrent call to Receive, TryReceive, Scan and/or TryScan may be active. An optional timeout in milliseconds. Defaults to -1 which corresponds to . An asynchronous computation that returns the received message or None if the timeout is exceeded. Like PostAndReply, but returns None if no reply within the timeout period. The function to incorporate the AsyncReplyChannel into the message to be sent. An optional timeout parameter (in milliseconds) to wait for a reply message. Defaults to -1 which corresponds to . The reply from the agent or None if the timeout expires. Starts the agent immediately on the current operating system thread. Creates and starts an agent immediately on the current operating system thread. The body function is used to generate the asynchronous computation executed by the agent. The function to produce an asynchronous computation that will be executed as the read loop for the MailboxProcessor when StartImmediately is called. A flag denotes will be thrown exception when is called after disposed. An optional cancellation token for the body. Defaults to Async.DefaultCancellationToken. The created MailboxProcessor. Creates and starts an agent immediately on the current operating system thread. The body function is used to generate the asynchronous computation executed by the agent. The function to produce an asynchronous computation that will be executed as the read loop for the MailboxProcessor when StartImmediately is called. An optional cancellation token for the body. Defaults to Async.DefaultCancellationToken. The created MailboxProcessor. Starts the agent. Creates and starts an agent. The body function is used to generate the asynchronous computation executed by the agent. The function to produce an asynchronous computation that will be executed as the read loop for the MailboxProcessor when Start is called. A flag denoting that an exception will be thrown when is called after has been disposed. An optional cancellation token for the body. Defaults to Async.DefaultCancellationToken. The created MailboxProcessor. Creates and starts an agent. The body function is used to generate the asynchronous computation executed by the agent. The function to produce an asynchronous computation that will be executed as the read loop for the MailboxProcessor when Start is called. An optional cancellation token for the body. Defaults to Async.DefaultCancellationToken. The created MailboxProcessor. Scans for a message by looking through messages in arrival order until scanner returns a Some value. Other messages remain in the queue. Returns None if a timeout is given and the timeout is exceeded. This method is for use within the body of the agent. For each agent, at most one concurrent reader may be active, so no more than one concurrent call to Receive, TryReceive, Scan and/or TryScan may be active. The function to return None if the message is to be skipped or Some if the message is to be processed and removed from the queue. An optional timeout in milliseconds. Defaults to -1 which corresponds to . An asynchronous computation that scanner built off the read message. Thrown when the timeout is exceeded. Waits for a message. This will consume the first message in arrival order. This method is for use within the body of the agent. This method is for use within the body of the agent. For each agent, at most one concurrent reader may be active, so no more than one concurrent call to Receive, TryReceive, Scan and/or TryScan may be active. An optional timeout in milliseconds. Defaults to -1 which corresponds to . An asynchronous computation that returns the received message. Thrown when the timeout is exceeded. Like AsyncPostAndReply, but returns None if no reply within the timeout period. The function to incorporate the AsyncReplyChannel into the message to be sent. An optional timeout parameter (in milliseconds) to wait for a reply message. Defaults to -1 which corresponds to . An asynchronous computation that will return the reply or None if the timeout expires. Posts a message to an agent and await a reply on the channel, synchronously. The message is generated by applying buildMessage to a new reply channel to be incorporated into the message. The receiving agent must process this message and invoke the Reply method on this reply channel precisely once. The function to incorporate the AsyncReplyChannel into the message to be sent. An optional timeout parameter (in milliseconds) to wait for a reply message. Defaults to -1 which corresponds to . The reply from the agent. Posts a message to an agent and await a reply on the channel, asynchronously. The message is generated by applying buildMessage to a new reply channel to be incorporated into the message. The receiving agent must process this message and invoke the Reply method on this reply channel precisely once. The function to incorporate the AsyncReplyChannel into the message to be sent. An optional timeout parameter (in milliseconds) to wait for a reply message. Defaults to -1 which corresponds to . An asynchronous computation that will wait for the reply from the agent. Posts a message to the message queue of the MailboxProcessor, asynchronously. The message to post. Disposes the agent's internal resources. Creates an agent. The body function is used to generate the asynchronous computation executed by the agent. This function is not executed until Start is called. The function to produce an asynchronous computation that will be executed as the read loop for the MailboxProcessor when Start is called. A flag denoting that an exception will be thrown when is called after has been disposed. An optional cancellation token for the body. Defaults to Async.DefaultCancellationToken. The created MailboxProcessor. Creates an agent. The body function is used to generate the asynchronous computation executed by the agent. This function is not executed until Start is called. The function to produce an asynchronous computation that will be executed as the read loop for the MailboxProcessor when Start is called. An optional cancellation token for the body. Defaults to Async.DefaultCancellationToken. The created MailboxProcessor. A message-processing agent which executes an asynchronous computation. The agent encapsulates a message queue that supports multiple-writers and a single reader agent. Writers send messages to the agent by using the Post method and its variations. The agent may wait for messages using the Receive or TryReceive methods or scan through all available messages using the Scan or TryScan method. Agents Sends a reply to a PostAndReply message. The value to send. A handle to a capability to reply to a PostAndReply message. Agents Forces the execution of this value and return its result. Same as Value. Mutual exclusion is used to prevent other threads also computing the value. The value of the Lazy object. Creates a lazy computation that evaluates to the given value when forced. The input value. The created Lazy object. Creates a lazy computation that evaluates to the result of the given function when forced. The function to provide the value when needed. The created Lazy object. Extensions related to Lazy values. Lazy Computation Returns an asynchronous computation that, when run, will wait for the download of the given URI to specified file. The URI to retrieve. The file name to save download to. An asynchronous computation that will wait for the download of the URI to specified file. open System.Net open System let client = new WebClient() Uri("https://www.w3.com") |> fun x -> client.AsyncDownloadFile(x, "output.html") |> Async.RunSynchronously This will download the server response as a file and output it as output.html Returns an asynchronous computation that, when run, will wait for the download of the given URI. The URI to retrieve. An asynchronous computation that will wait for the download of the URI. open System.Net open System.Text open System let client = new WebClient() client.AsyncDownloadData(Uri("https://www.w3.org")) |> Async.RunSynchronously |> Encoding.ASCII.GetString Downloads the data in bytes and decodes it to a string. Returns an asynchronous computation that, when run, will wait for the download of the given URI. The URI to retrieve. An asynchronous computation that will wait for the download of the URI. open System let client = new WebClient() Uri("https://www.w3.org") |> client.AsyncDownloadString |> Async.RunSynchronously This will download the server response from https://www.w3.org Returns an asynchronous computation that, when run, will wait for a response to the given WebRequest. An asynchronous computation that waits for response to the WebRequest. open System.Net open System.IO let responseStreamToString = fun (responseStream : WebResponse) -> let reader = new StreamReader(responseStream.GetResponseStream()) reader.ReadToEnd() let webRequest = WebRequest.Create("https://www.w3.org") let result = webRequest.AsyncGetResponse() |> Async.RunSynchronously |> responseStreamToString Gets the web response asynchronously and converts response stream to string A module of extension members providing asynchronous operations for some basic Web operations. Async Programming Connects a listener function to the observable. The listener will be invoked for each observation. The listener can be removed by calling Dispose on the returned IDisposable object. The function to be called for each observation. An object that will remove the listener if disposed. Permanently connects a listener function to the observable. The listener will be invoked for each observation. The function to be called for each observation. Returns an asynchronous computation that will write the given bytes to the stream. The buffer to write from. An optional offset as a number of bytes in the stream. An optional number of bytes to write to the stream. An asynchronous computation that will write the given bytes to the stream. Thrown when the sum of offset and count is longer than the buffer length. Thrown when offset or count is negative. Returns an asynchronous computation that will read the given number of bytes from the stream. The number of bytes to read. An asynchronous computation that returns the read byte array when run. Returns an asynchronous computation that will read from the stream into the given buffer. The buffer to read into. An optional offset as a number of bytes in the stream. An optional number of bytes to read from the stream. An asynchronous computation that will read from the stream into the given buffer. Thrown when the sum of offset and count is longer than the buffer length. Thrown when offset or count is negative. A module of extension members providing asynchronous operations for some basic CLI types related to concurrency and I/O. Async Programming The F# compiler emits calls to this function to implement the try/with construct for F# async expressions. The async activation. The computation to protect. The exception filter. A value indicating asynchronous execution. The F# compiler emits calls to this function to implement the try/finally construct for F# async expressions. The async activation. The computation to protect. The finally code. A value indicating asynchronous execution. The F# compiler emits calls to this function to implement the let! construct for F# async expressions. The async activation. The first part of the computation. A function returning the second part of the computation. An async activation suitable for running part1 of the asynchronous execution. The F# compiler emits calls to this function to implement constructs for F# async expressions. The async activation. The result of the first part of the computation. A function returning the second part of the computation. A value indicating asynchronous execution. The F# compiler emits calls to this function to implement constructs for F# async expressions. The async computation. The async activation. A value indicating asynchronous execution. The F# compiler emits calls to this function to implement F# async expressions. The body of the async computation. The async computation. Entry points for generated code Async Internals The entry point for the dynamic implementation of the corresponding operation. Do not use directly, only used when executing quotations that involve tasks or other reflective execution of F# code. Specifies a unit of task code which draws a result from a task. Specifies a unit of task code which draws a result from a task then calls a continuation. Contains high-priority overloads for the `task` computation expression builder. Specifies a unit of task code which draws a result from an F# async value. Specifies a unit of task code which draws a result from an F# async value then calls a continuation. Contains medium-priority overloads for the `task` computation expression builder. Specifies a unit of task code which binds to the resource implementing IDisposable and disposes it synchronously The entry point for the dynamic implementation of the corresponding operation. Do not use directly, only used when executing quotations that involve tasks or other reflective execution of F# code. Specifies a unit of task code which draws its result from a task-like value satisfying the GetAwaiter pattern. Specifies a unit of task code which draws a result from a task-like value satisfying the GetAwaiter pattern and calls a continuation. Contains low-priority overloads for the `task` computation expression builder. Builds a task using computation expression syntax which switches to execute on a background thread if not already doing so. If the task is created on a foreground thread (where is non-null) its body is executed on a background thread using . If created on a background thread (where is null) it is executed immediately on that thread. Builds a task using computation expression syntax. Contains the `task` computation expression builder. Returns a new event that triggers on the second and subsequent triggerings of the input event. The Nth triggering of the input event passes the arguments from the N-1th and Nth triggering as a pair. The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. The input event. An event that triggers on pairs of consecutive values passed from the source event. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let pairWise = Event.pairwise timer let extractPair (pair: Timers.ElapsedEventArgs * Timers.ElapsedEventArgs) = let leftPair, rightPair = pair printfn $"(Left): {leftPair.SignalTime} (Right): {rightPair.SignalTime}" pairWise.Subscribe(extractPair) |> ignore Console.ReadLine() |> ignore The sample will output the timer event every second: (Left): 2/14/2022 11:58:46 PM (Right): 2/14/2022 11:58:46 PM (Left): 2/14/2022 11:58:46 PM (Right): 2/14/2022 11:58:47 PM (Left): 2/14/2022 11:58:47 PM (Right): 2/14/2022 11:58:48 PM Runs the given function each time the given event is triggered. The function to call when the event is triggered. The input event. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 Event.add (fun (event: Timers.ElapsedEventArgs) -> printfn $"{event.SignalTime} ") timer Console.ReadLine() |> ignore The sample will output the timer event every second: 2/14/2022 11:52:05 PM 2/14/2022 11:52:06 PM 2/14/2022 11:52:07 PM 2/14/2022 11:52:08 PM Returns a new event consisting of the results of applying the given accumulating function to successive values triggered on the input event. An item of internal state records the current value of the state parameter. The internal state is not locked during the execution of the accumulation function, so care should be taken that the input IEvent not triggered by multiple threads simultaneously. The function to update the state with each event value. The initial state. The input event. An event that fires on the updated state values. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let multiplyBy number = fun (timerEvent: Timers.ElapsedEventArgs) -> number * timerEvent.SignalTime./// Second let initialState = 2 let scan = Event.scan multiplyBy initialState timer scan.Subscribe(fun x -> printf "%A " x) |> ignore Console.ReadLine() |> ignore The sample will output depending on your timestamp. It will multiply the seconds with an initial state of 2: 106 5724 314820 17629920 1004905440 -1845026624 -1482388416 Returns a new event which fires on a selection of messages from the original event. The selection function takes an original message to an optional new message. The function to select and transform event values to pass on. The input event. An event that fires only when the chooser returns Some. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let getEvenSeconds (number: Timers.ElapsedEventArgs) = match number with | _ when number.SignalTime.Second % 2 = 0 -> Some number.SignalTime | _ -> None let evenSecondsEvent = Event.choose getEvenSeconds timer evenSecondsEvent.Subscribe(fun x -> printfn $"{x} ") |> ignore Console.ReadLine() |> ignore The sample will output: 2/15/2022 12:04:04 AM 2/15/2022 12:04:06 AM 2/15/2022 12:04:08 AM Returns a new event that listens to the original event and triggers the first resulting event if the application of the function to the event arguments returned a Choice1Of2, and the second event if it returns a Choice2Of2. The function to transform event values into one of two types. The input event. A tuple of events. The first fires whenever splitter evaluates to Choice1of1 and the second fires whenever splitter evaluates to Choice2of2. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let bySeconds (timerEvent: Timers.ElapsedEventArgs) = match timerEvent.SignalTime.Second % 2 = 0 with | true -> Choice1Of2 timerEvent.SignalTime.Second | false -> Choice2Of2 $"{timerEvent.SignalTime.Second} is not an even num ber" let evenSplit, printOddNumbers = Event.split bySeconds timer let printOutput event functionName = Event.add (fun output -> printfn $"{functionName} - Split output: {output}. /// Type: {output.GetType()}") event printOutput evenSplit (nameof evenSplit) |> ignore printOutput printOddNumbers (nameof printOddNumbers) |> ignore Console.ReadLine() |> ignore The sample will split the events by even or odd seconds: evenSplit - Split output: 44. Type: System.Int32 printOddNumbers - Split output: 45 is not an even number. Type: System.String evenSplit - Split output: 46. Type: System.Int32 printOddNumbers - Split output: 47 is not an even number. Type: System.String evenSplit - Split output: 48. Type: System.Int32 printOddNumbers - Split output: 49 is not an even number. Type: System.String Returns a new event that listens to the original event and triggers the first resulting event if the application of the predicate to the event arguments returned true, and the second event if it returned false. The function to determine which output event to trigger. The input event. A tuple of events. The first is triggered when the predicate evaluates to true and the second when the predicate evaluates to false. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let getEvenSeconds (number: Timers.ElapsedEventArgs) = match number with | _ when number.SignalTime.Second % 2 = 0 -> true | _ -> false let leftPartition, rightPartition = Event.partition getEvenSeconds timer leftPartition.Subscribe(fun x -> printfn $"Left partition: {x.SignalTime}") |> ignore rightPartition.Subscribe(fun x -> printfn $"Right partition: {x.SignalTime}") |> ignore Console.ReadLine() |> ignore The sample will partition into two events if it is even or odd seconds: Right partition: 2/15/2022 12:00:27 AM Left partition: 2/15/2022 12:00:28 AM Right partition: 2/15/2022 12:00:29 AM Left partition: 2/15/2022 12:00:30 AM Right partition: 2/15/2022 12:00:31 AM Returns a new event that listens to the original event and triggers the resulting event only when the argument to the event passes the given function. The function to determine which triggers from the event to propagate. The input event. An event that only passes values that pass the predicate. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let getEvenSeconds (number: Timers.ElapsedEventArgs) = match number with | _ when number.SignalTime.Second % 2 = 0 -> true | _ -> false let evenSecondsEvent = Event.filter getEvenSeconds timer evenSecondsEvent.Subscribe(fun x -> printfn $"{x} ") |> ignore Console.ReadLine() |> ignore The sample will only output even seconds: 2/15/2022 12:03:08 AM 2/15/2022 12:03:10 AM 2/15/2022 12:03:12 AM 2/15/2022 12:03:14 AM Returns a new event that passes values transformed by the given function. The function to transform event values. The input event. An event that passes the transformed values. open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let timer = createTimer 1000 let transformSeconds (number: Timers.ElapsedEventArgs) = match number with | _ when number.SignalTime.Second % 2 = 0 -> 100 | _ -> -500 let evenSecondsEvent = Event.map transformSeconds timer evenSecondsEvent.Subscribe(fun x -> printf $"{x} ") |> ignore Console.ReadLine() |> ignore The sample will transform the seconds if it's even or odd number and the output is: -500 100 -500 100 -500 100 Fires the output event when either of the input events fire. The first input event. The second input event. An event that fires when either of the input events fire. open System.Reactive.Linq open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true timer.Elapsed let oneSecondTimer = createTimer 1000 let fiveSecondsTimer = createTimer 5000 let result = Event.merge oneSecondTimer fiveSecondsTimer result.Subscribe(fun output -> printfn $"Output - {output.SignalTime} ") |> ignore Console.ReadLine() |> ignore The sample will output: Output - 2/15/2022 12:10:40 AM Output - 2/15/2022 12:10:41 AM Output - 2/15/2022 12:10:41 AM Output - 2/15/2022 12:10:42 AM Output - 2/15/2022 12:10:43 AM Contains operations for working with values of type . Events and Observables Returns a new observable that triggers on the second and subsequent triggerings of the input observable. The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. For each observer, the registered intermediate observing object is not thread safe. That is, observations arising from the source must not be triggered concurrently on different threads. The input Observable. An Observable that triggers on successive pairs of observations from the input Observable. /// open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let pairWise = Observable.pairwise observableNumbers pairWise.Subscribe(fun pair -> printf $"{pair} ") |> ignore The sample evaluates to: (1, 2), (2, 3), (3, 4), (4, 5) Creates an observer which subscribes to the given observable and which calls the given function for each observation. The function to be called on each observation. The input Observable. An object that will remove the callback if disposed. open System.Reactive.Linq let numbers = seq { 1..3 } let observableNumbers = Observable.ToObservable numbers let printOutput observable = use subscription = Observable.subscribe (fun x -> printfn "%A" x) observable subscription printOutput observableNumbers |> ignore The sample evaluates to: 1, 2, 3 Creates an observer which permanently subscribes to the given observable and which calls the given function for each observation. The function to be called on each observation. The input Observable. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let multiplyByTwo = fun number -> printf $"{number * 2} " Observable.add multiplyByTwo observableNumbers The sample evaluates to: 2 4 6 8 10 Returns an observable which, for each observer, allocates an item of state and applies the given accumulating function to successive values arising from the input. The returned object will trigger observations for each computed state value, excluding the initial value. The returned object propagates all errors arising from the source and completes when the source completes. For each observer, the registered intermediate observing object is not thread safe. That is, observations arising from the source must not be triggered concurrently on different threads. The function to update the state with each observation. The initial state. The input Observable. An Observable that triggers on the updated state values. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let multiplyBy number = fun y -> number * y let initialState = 2 let scan = Observable.scan multiplyBy initialState observableNumbers scan.Subscribe(fun x -> printf "%A " x) |> ignore The sample evaluates to: 2 4 12 48 240 Returns an observable which chooses a projection of observations from the source using the given function. The returned object will trigger observations x for which the splitter returns Some x. The returned object also propagates all errors arising from the source and completes when the source completes. The function that returns Some for observations to be propagated and None for observations to ignore. The input Observable. An Observable that only propagates some of the observations from the source. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let getOddNumbers number = match number with | _ when number % 2 = 0 -> None | _ -> Some number let map = Observable.choose getOddNumbers observableNumbers map.Subscribe(fun x -> printf $"{x} ") |> ignore The sample will output: 1 3 5 Returns two observables which split the observations of the source by the given function. The first will trigger observations x for which the splitter returns Choice1Of2 x. The second will trigger observations y for which the splitter returns Choice2Of2 y The splitter is executed once for each subscribed observer. Both also propagate error observations arising from the source and each completes when the source completes. The function that takes an observation an transforms it into one of the two output Choice types. The input Observable. A tuple of Observables. The first triggers when splitter returns Choice1of2 and the second triggers when splitter returns Choice2of2. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let getEvenNumbers number = match number % 2 = 0 with | true -> Choice1Of2 number | false -> Choice2Of2 $"{number} is not an even number" let evenSplit, printOddNumbers = Observable.split getEvenNumbers observableNumbers let printOutput observable functionName = use subscription = Observable.subscribe (fun output -> printfn $"{functionName} - Split output: {output}. Type: {output.GetType()}") observable subscription printOutput evenSplit (nameof evenSplit) |> ignore printOutput printOddNumbers (nameof printOddNumbers) |> ignore The sample evaluates to: evenSplit - Split output: 2. Type: System.Int32 evenSplit - Split output: 4. Type: System.Int32 printOddNumbers - Split output: 1 is not an even number. Type: System.String printOddNumbers - Split output: 3 is not an even number. Type: System.String printOddNumbers - Split output: 5 is not an even number. Type: System.String Returns two observables which partition the observations of the source by the given function. The first will trigger observations for those values for which the predicate returns true. The second will trigger observations for those values where the predicate returns false. The predicate is executed once for each subscribed observer. Both also propagate all error observations arising from the source and each completes when the source completes. The function to determine which output Observable will trigger a particular observation. The input Observable. A tuple of Observables. The first triggers when the predicate returns true, and the second triggers when the predicate returns false. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let isEvenNumber = fun number -> number % 2 = 0 let leftPartition, rightPartition = Observable.partition isEvenNumber observableNumbers leftPartition.Subscribe(fun x -> printfn $"Left partition: {x}") |> ignore rightPartition.Subscribe(fun x -> printfn $"Right partition: {x}") |> ignore The sample evaluates to: Left partition: 2, 4, Right partition: 1, 3, 5 Returns an observable which filters the observations of the source by the given function. The observable will see only those observations for which the predicate returns true. The predicate is executed once for each subscribed observer. The returned object also propagates error observations arising from the source and completes when the source completes. The function to apply to observations to determine if it should be kept. The input Observable. An Observable that filters observations based on filter. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let getEvenNumbers = fun number -> number % 2 = 0 let map = Observable.filter multiplyByTwo observableNumbers map.Subscribe(fun x -> printf $"{x} ") |> ignore The sample will output: 2 4 Returns an observable which transforms the observations of the source by the given function. The transformation function is executed once for each subscribed observer. The returned object also propagates error observations arising from the source and completes when the source completes. The function applied to observations from the source. The input Observable. An Observable of the type specified by mapping. open System.Reactive.Linq let numbers = seq { 1..5 } let observableNumbers = Observable.ToObservable numbers let multiplyByTwo = fun number -> number * 2 let map = Observable.map multiplyByTwo observableNumbers map.Subscribe(fun x -> printf $"{x} ") |> ignore The sample will output: 2 4 6 8 10 Returns an observable for the merged observations from the sources. The returned object propagates success and error values arising from either source and completes when both the sources have completed. For each observer, the registered intermediate observing object is not thread safe. That is, observations arising from the sources must not be triggered concurrently on different threads. The first Observable. The second Observable. An Observable that propagates information from both sources. open System.Reactive.Linq open System let createTimer interval = let timer = new Timers.Timer(interval) timer.AutoReset <- true timer.Enabled <- true Observable.Create(fun observer -> timer.Elapsed.Subscribe(observer)) let observableFirstTimer = createTimer 1000 let observableSecondTimer = createTimer 3000 let result = Observable.merge observableFirstTimer observableSecondTimer result.Subscribe(fun output -> printfn $"Output - {output.SignalTime} ") |> ignore Console.ReadLine() |> ignore The sample will merge all events at a given interval and output it to the stream: Output - 2/5/2022 3:49:37 AM Output - 2/5/2022 3:49:38 AM Output - 2/5/2022 3:49:39 AM Output - 2/5/2022 3:49:39 AM Output - 2/5/2022 3:49:40 AM Output - 2/5/2022 3:49:41 AM Output - 2/5/2022 3:49:42 AM Output - 2/5/2022 3:49:42 AM Contains operations for working with first class event and other observable objects. Events and Observables A method used to support the F# query syntax. Returns an empty sequence that has the specified type argument. A method used to support the F# query syntax. Returns a sequence that contains the specified values. A method used to support the F# query syntax. Returns a sequence of length one that contains the specified value. A query operator that selects those elements based on a specified predicate. A query operator that performs a subsequent ordering of the elements selected so far in descending order by the given nullable sorting key. This operator may only be used immediately after a 'sortBy', 'sortByDescending', 'thenBy' or 'thenByDescending', or their nullable variants. A query operator that performs a subsequent ordering of the elements selected so far in ascending order by the given nullable sorting key. This operator may only be used immediately after a 'sortBy', 'sortByDescending', 'thenBy' or 'thenByDescending', or their nullable variants. A query operator that performs a subsequent ordering of the elements selected so far in descending order by the given sorting key. This operator may only be used immediately after a 'sortBy', 'sortByDescending', 'thenBy' or 'thenByDescending', or their nullable variants. A query operator that performs a subsequent ordering of the elements selected so far in ascending order by the given sorting key. This operator may only be used immediately after a 'sortBy', 'sortByDescending', 'thenBy' or 'thenByDescending', or their nullable variants. A query operator that selects elements from a sequence as long as a specified condition is true, and then skips the remaining elements. A query operator that selects a specified number of contiguous elements from those selected so far. A query operator that selects a nullable value for each element selected so far and returns the sum of these values. If any nullable does not have a value, it is ignored. A query operator that selects a value for each element selected so far and returns the sum of these values. A method used to support the F# query syntax. Inputs to queries are implicitly wrapped by a call to one of the overloads of this method. A method used to support the F# query syntax. Inputs to queries are implicitly wrapped by a call to one of the overloads of this method. A query operator that sorts the elements selected so far in descending order by the given nullable sorting key. A query operator that sorts the elements selected so far in ascending order by the given nullable sorting key. A query operator that sorts the elements selected so far in descending order by the given sorting key. A query operator that sorts the elements selected so far in ascending order by the given sorting key. A query operator that bypasses elements in a sequence as long as a specified condition is true and then selects the remaining elements. A query operator that bypasses a specified number of the elements selected so far and selects the remaining elements. A query operator that projects each of the elements selected so far. A method used to support the F# query syntax. Runs the given quotation as a query using LINQ IQueryable rules. A method used to support the F# query syntax. Indicates that the query should be passed as a quotation to the Run method. A query operator that selects the element at a specified index amongst those selected so far. A query operator that selects a nullable value for each element selected so far and returns the minimum of these values. If any nullable does not have a value, it is ignored. A query operator that selects a value for each element selected so far and returns the minimum resulting value. A query operator that selects a nullable value for each element selected so far and returns the maximum of these values. If any nullable does not have a value, it is ignored. A query operator that selects a value for each element selected so far and returns the maximum resulting value. A query operator that correlates two sets of selected values based on matching keys and groups the results. If any group is empty, a group with a single default value is used instead. Normal usage is 'leftOuterJoin y in elements2 on (key1 = key2) into group'. A query operator that selects the last element of those selected so far, or a default value if no element is found. A query operator that selects the last element of those selected so far. A query operator that correlates two sets of selected values based on matching keys. Normal usage is 'join y in elements2 on (key1 = key2)'. A query operator that selects the first element of those selected so far, or a default value if the sequence contains no elements. A query operator that selects the first element from those selected so far. A query operator that selects a value for each element selected so far and groups the elements by the given key. A query operator that correlates two sets of selected values based on matching keys and groups the results. Normal usage is 'groupJoin y in elements2 on (key1 = key2) into group'. A query operator that groups the elements selected so far according to a specified key selector. A method used to support the F# query syntax. Projects each element of a sequence to another sequence and combines the resulting sequences into one sequence. A query operator that selects the first element selected so far that satisfies a specified condition. A query operator that determines whether any element selected so far satisfies a condition. A query operator that selects the single, specific element of those selected so far, or a default value if that element is not found. A query operator that selects the single, specific element selected so far A query operator that selects distinct elements from the elements selected so far. A query operator that returns the number of selected elements. A query operator that determines whether the selected elements contains a specified element. A query operator that selects a nullable value for each element selected so far and returns the average of these values. If any nullable does not have a value, it is ignored. A query operator that selects a value for each element selected so far and returns the average of these values. A query operator that determines whether all elements selected so far satisfies a condition. Create an instance of this builder. Use 'query { ... }' to use the query syntax. The type used to support the F# query syntax. Use 'query { ... }' to use the query syntax. See also <a href="https://learn.microsoft.com/dotnet/fsharp/language-reference/query-expressions">F# Query Expressions</a> in the F# Language Guide. A property used to support the F# query syntax. A method used to support the F# query syntax. A partial input or result in an F# query. This type is used to support the F# query syntax. Library functionality for F# query syntax and interoperability with .NET LINQ Expressions. See also F# Query Expressions in the F# Language Guide. Converts the argument to character. Numeric inputs are converted according to the UTF-16 encoding for characters. The operation requires an appropriate static conversion method on the input type. The input value. The converted char. open System open FSharp.Linq.NullableOperators Nullable.char (Nullable<int>()) // evaluates to Nullable<char>() Nullable.char (Nullable<int>(64)) // evaluates to Nullable<char>('@') Converts the argument to System.Decimal using a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted decimal. open System open FSharp.Linq.NullableOperators Nullable.decimal (Nullable<int>()) // evaluates to Nullable<decimal>() Nullable.decimal (Nullable<int>(3)) // evaluates to Nullable<decimal>(3.0M) Converts the argument to unsigned native integer using a direct conversion for all primitive numeric types. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted unativeint open System open FSharp.Linq.NullableOperators Nullable.unativeint (Nullable<int>()) // evaluates to Nullable<unativeint>() Nullable.unativeint (Nullable<int>(3)) // evaluates to Nullable<unativeint>(3un) Converts the argument to signed native integer. This is a direct conversion for all primitive numeric types. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted nativeint open System open FSharp.Linq.NullableOperators Nullable.nativeint (Nullable<int>()) // evaluates to Nullable<nativeint>() Nullable.nativeint (Nullable<int>(3)) // evaluates to Nullable<nativeint>(3n) Converts the argument to 64-bit float. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted float open System open FSharp.Linq.NullableOperators Nullable.double (Nullable<int>()) // evaluates to Nullable<double>() Nullable.double (Nullable<int>(3)) // evaluates to Nullable<double>(3.0) Converts the argument to 32-bit float. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted float32 open System open FSharp.Linq.NullableOperators Nullable.single (Nullable<int>()) // evaluates to Nullable<float32>() Nullable.single (Nullable<int>(3)) // evaluates to Nullable<float32>(3.0f) Converts the argument to 64-bit float. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted float open System open FSharp.Linq.NullableOperators Nullable.float (Nullable<int>()) // evaluates to Nullable<float>() Nullable.float (Nullable<int>(3)) // evaluates to Nullable<float>(3.0) Converts the argument to 32-bit float. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted float32 open System open FSharp.Linq.NullableOperators Nullable.float32 (Nullable<int>()) // evaluates to Nullable<float32>() Nullable.float32 (Nullable<int>(3)) // evaluates to Nullable<float32>(3.0f) Converts the argument to unsigned 64-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted uint64 open System open FSharp.Linq.NullableOperators Nullable.uint64 (Nullable<int>()) // evaluates to Nullable<uint64>() Nullable.uint64 (Nullable<int>(3)) // evaluates to Nullable<uint64>(3UL) Converts the argument to signed 64-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted int64 open System open FSharp.Linq.NullableOperators Nullable.int64 (Nullable<int>()) // evaluates to Nullable<int64>() Nullable.int64 (Nullable<int>(3)) // evaluates to Nullable<int64>(3L) Converts the argument to unsigned 32-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted uint32 open System open FSharp.Linq.NullableOperators Nullable.uint32 (Nullable<int>()) // evaluates to Nullable<uint32>() Nullable.uint32 (Nullable<int>(3)) // evaluates to Nullable(3u) Converts the argument to signed 32-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted int32 open System open FSharp.Linq.NullableOperators Nullable.int32 (Nullable<int64>()) // evaluates to Nullable<int32>() Nullable.int32 (Nullable<int64>(3)) // evaluates to Nullable(3) Converts the argument to a particular enum type. The input value. The converted enum type. open System open FSharp.Linq.NullableOperators Nullable.enum<DayOfWeek> (Nullable<int>()) // evaluates to Nullable<uint>() Nullable.enum<DayOfWeek> (Nullable<int>(3)) // evaluates to Nullable<DayOfWeek>(Wednesday) Converts the argument to an unsigned 32-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted unsigned integer open System open FSharp.Linq.NullableOperators Nullable.uint (Nullable<int>()) // evaluates to Nullable<uint>() Nullable.uint (Nullable<int>(3)) // evaluates to Nullable(3u) Converts the argument to signed 32-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted int open System open FSharp.Linq.NullableOperators Nullable.int (Nullable<int64>()) // evaluates to Nullable<int>() Nullable.int (Nullable<int64>(3)) // evaluates to Nullable(3) Converts the argument to unsigned 16-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted uint16 open System open FSharp.Linq.NullableOperators Nullable.uint16 (Nullable<int>()) // evaluates to Nullable<uint16>() Nullable.uint16 (Nullable<int>(3)) // evaluates to Nullable(3us) Converts the argument to signed 16-bit integer. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted int16 open System open FSharp.Linq.NullableOperators Nullable.int16 (Nullable<int>()) // evaluates to Nullable<int16>() Nullable.int16 (Nullable<int>(3)) // evaluates to Nullable(3s) Converts the argument to signed byte. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted sbyte open System open FSharp.Linq.NullableOperators Nullable.int8 (Nullable<int>()) // evaluates to Nullable<sbyte>() Nullable.int8 (Nullable<int>(3)) // evaluates to Nullable(3y) Converts the argument to signed byte. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted sbyte open System open FSharp.Linq.NullableOperators Nullable.sbyte (Nullable<int>()) // evaluates to Nullable<sbyte>() Nullable.sbyte (Nullable<int>(3)) // evaluates to Nullable(3y) Converts the argument to byte. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted byte open System open FSharp.Linq.NullableOperators Nullable.uint8 (Nullable<int>()) // evaluates to Nullable<byte>() Nullable.uint8 (Nullable<int>(3)) // evaluates to Nullable(3uy) Converts the argument to byte. This is a direct conversion for all primitive numeric types. The operation requires an appropriate static conversion method on the input type. The input value. The converted byte open System open FSharp.Linq.NullableOperators Nullable.byte (Nullable<int>()) // evaluates to Nullable<byte>() Nullable.byte (Nullable<int>(3)) // evaluates to Nullable(3uy) Functions for converting nullable values The division operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The division operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The division operator where a nullable value appears on the left This operator is primarily for use in F# queries See the other operators in this module for related examples. The modulus operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The modulus operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The modulus operator where a nullable value appears on the left This operator is primarily for use in F# queries See the other operators in this module for related examples. The multiplication operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The multiplication operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The multiplication operator where a nullable value appears on the left This operator is primarily for use in F# queries See the other operators in this module for related examples. The subtraction operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The subtraction operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The subtraction operator where a nullable value appears on the left This operator is primarily for use in F# queries See the other operators in this module for related examples. The addition operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The addition operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The addition operator where a nullable value appears on the left This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<>' operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The '=' operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<' operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<=' operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The '>' operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The '>=' operator where a nullable value appears on both left and right sides This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<>' operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The '=' operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<' operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<=' operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The '>' operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The '>=' operator where a nullable value appears on the right This operator is primarily for use in F# queries See the other operators in this module for related examples. The '<>' operator where a nullable value appears on the left This operator is primarily for use in F# queries open FSharp.Linq.NullableOperators Nullable(3) ?<>= 4 // true Nullable(4) ?<>= 4 // false Nullable() ?<> 4 // true The '=' operator where a nullable value appears on the left This operator is primarily for use in F# queries open FSharp.Linq.NullableOperators Nullable(3) ?= 4 // false Nullable(4) ?= 4 // true Nullable() ?= 4 // false The '<' operator where a nullable value appears on the left This operator is primarily for use in F# queries open FSharp.Linq.NullableOperators Nullable(3) ?< 4 // true Nullable(4) ?< 4 // false Nullable() ?< 4 // false The '<=' operator where a nullable value appears on the left This operator is primarily for use in F# queries open FSharp.Linq.NullableOperators Nullable(3) ?<= 4 // true Nullable(5) ?<= 4 // false Nullable() ?<= 4 // false The '>' operator where a nullable value appears on the left This operator is primarily for use in F# queries open FSharp.Linq.NullableOperators Nullable(3) ?> 4 // false Nullable(5) ?> 4 // true Nullable() ?> 4 // false The '>=' operator where a nullable value appears on the left This operator is primarily for use in F# queries open FSharp.Linq.NullableOperators Nullable(3) ?>= 4 // false Nullable(4) ?>= 4 // true Nullable() ?>= 4 // false Operators for working with nullable values, primarily used on F# queries. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. This type shouldn't be used directly from user code. A type used to reconstruct a grouping after applying a mutable->immutable mapping transformation on a result of a query. A runtime helper used to evaluate nested quotation literals. A runtime helper used to evaluate nested quotation literals. Evaluates a subset of F# quotations by first converting to a LINQ expression, for the subset of LINQ expressions represented by the expression syntax in the C# language. Converts a subset of F# quotations to a LINQ expression, for the subset of LINQ expressions represented by the expression syntax in the C# language. Converts a subset of F# quotations to a LINQ expression, for the subset of LINQ expressions represented by the expression syntax in the C# language. When used in a quotation, this function indicates a specific conversion should be performed when converting the quotation to a LINQ expression. This function should not be called directly. When used in a quotation, this function indicates a specific conversion should be performed when converting the quotation to a LINQ expression. This function should not be called directly. When used in a quotation, this function indicates a specific conversion should be performed when converting the quotation to a LINQ expression. This function should not be called directly. Contains functionality to convert F# quotations to LINQ expression trees. Library functionality associated with converting F# quotations to .NET LINQ expression trees. The generic MethodInfo for Select function Describes how we got from productions of immutable objects to productions of anonymous objects, with enough information that we can invert the process in final query results. Given the expression part of a "yield" or "select" which produces a result in terms of immutable tuples or immutable records, generate an equivalent expression yielding anonymous objects. Also return the conversion for the immutable-to-mutable correspondence so we can reverse this later. Simplify gets of tuples and gets of record fields. Cleanup the use of property-set object constructions in leaf expressions that form parts of F# queries. Given an type involving immutable tuples and records, logically corresponding to the type produced at a "yield" or "select", convert it to a type involving anonymous objects according to the conversion data. Recognize anonymous type construction written using 'new AnonymousObject(<e1>, <e2>, ...)' Recognize object construction written using 'new O(Prop1 = <e>, Prop2 = <e>, ...)' Tests whether a list consists only of assignments of properties of the given variable, null values (ignored) and ends by returning the given variable (pattern returns only property assignments) Recognize sequential series written as (... ((<e>; <e>); <e>); ...) A method used to support the F# query syntax. Runs the given quotation as a query using LINQ IEnumerable rules. A module used to support the F# query syntax. A method used to support the F# query syntax. Runs the given quotation as a query using LINQ rules. A module used to support the F# query syntax. Contains modules used to support the F# query syntax. A synonym for henry, the SI unit of inductance A synonym for katal, the SI unit of catalytic activity A synonym for sievert, the SI unit of does equivalent A synonym for gray, the SI unit of absorbed dose A synonym for becquerel, the SI unit of activity referred to a radionuclide A synonym for lux, the SI unit of illuminance A synonym for lumen, the SI unit of luminous flux A synonym for tesla, the SI unit of magnetic flux density A synonym for weber, the SI unit of magnetic flux A synonym for UnitNames.ohm, the SI unit of electric resistance. A synonym for siemens, the SI unit of electric conductance A synonym for farad, the SI unit of capacitance A synonym for volt, the SI unit of electric potential difference, electromotive force A synonym for coulomb, the SI unit of electric charge, amount of electricity A synonym for watt, the SI unit of power, radiant flux A synonym for joule, the SI unit of energy, work, amount of heat A synonym for pascal, the SI unit of pressure, stress A synonym for newton, the SI unit of force A synonym for hertz, the SI unit of frequency A synonym for candela, the SI unit of luminous intensity A synonym for mole, the SI unit of amount of substance A synonym for kelvin, the SI unit of thermodynamic temperature A synonym for ampere, the SI unit of electric current A synonym for second, the SI unit of time A synonym for kilogram, the SI unit of mass A synonym for Metre, the SI unit of length The SI unit of catalytic activity The SI unit of does equivalent The SI unit of absorbed dose The SI unit of activity referred to a radionuclide The SI unit of illuminance The SI unit of luminous flux The SI unit of inductance The SI unit of magnetic flux density The SI unit of magnetic flux The SI unit of electric conductance The SI unit of electric resistance The SI unit of capacitance The SI unit of electric potential difference, electromotive force The SI unit of electric charge, amount of electricity The SI unit of power, radiant flux The SI unit of energy, work, amount of heat The SI unit of pressure, stress The SI unit of force The SI unit of frequency The SI unit of luminous intensity The SI unit of amount of substance The SI unit of thermodynamic temperature The SI unit of electric current The SI unit of time The SI unit of mass The SI unit of length The SI unit of length Represents an Common IL (Intermediate Language) Signature Pointer. This type should only be used when writing F# code that interoperates with other .NET languages that use generic Common IL Signature Pointers. Use of this type in F# code may result in unverifiable code being generated. Because of the rules of Common IL Signature Pointers, you cannot use this type in generic type parameters, resulting in compiler errors. As a result, you should convert this type to for use in F#. Note that Common IL Signature Pointers exposed by other .NET languages are converted to or automatically by F#, and F# also shows generic-specialized typed native pointers correctly to other .NET languages as Common IL Signature Pointers. However, generic typed native pointers are shown as to other .NET languages. For other languages to interpret generic F# typed native pointers correctly, you should expose this type or instead of . Values of this type can be generated by the functions in the NativeInterop.NativePtr module. ByRef and Pointer Types Represents an untyped unmanaged pointer in F# code. This type should only be used when writing F# code that interoperates with native code. Use of this type in F# code may result in unverifiable code being generated. Conversions to and from the type may be required. Values of this type can be generated by the functions in the NativeInterop.NativePtr module. ByRef and Pointer Types Represents an unmanaged pointer in F# code. This type should only be used when writing F# code that interoperates with native code. Use of this type in F# code may result in unverifiable code being generated. Conversions to and from the type may be required. Values of this type can be generated by the functions in the NativeInterop.NativePtr module. ByRef and Pointer Types Single dimensional, zero-based arrays, written int array, string array etc. Use the values in the module to manipulate values of this type, or the notation arr.[x] to get/set array values. Basic Types Thirty-two dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Thirty-one dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Thirty dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-nine dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-eight dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-seven dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-six dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-five dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-four dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-three dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-two dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty-one dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twenty dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Nineteen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Eighteen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Seventeen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Sixteen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Fifteen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Fourteen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Thirteen dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Twelve dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Eleven dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Ten dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Nine dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Eight dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Seven dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Six dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Five dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Basic Types Four dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Use the values in the Array4D module to manipulate values of this type, or the notation arr.[x1,x2,x3,x4] to get and set array values. Basic Types Three dimensional arrays, typically zero-based. Non-zero-based arrays can be created using methods on the System.Array type. Use the values in the Array3D module to manipulate values of this type, or the notation arr.[x1,x2,x3] to get and set array values. Basic Types Two dimensional arrays, typically zero-based. Use the values in the Array2D module to manipulate values of this type, or the notation arr.[x,y] to get/set array values. Non-zero-based arrays can also be created using methods on the System.Array type. Basic Types Single dimensional, zero-based arrays, written int array, string array etc. Use the values in the Array module to manipulate values of this type, or the notation arr.[x] to get/set array values. Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Identical to . Basic Types An abbreviation for the CLI type . Identical to . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type . Basic Types An abbreviation for the CLI type or null. With the 'nullable reference types' feature, this is an alias to 'obj | null'. Basic Types An abbreviation for the CLI type . Basic Types Represents an Error or a Failure. The code failed with a value of 'TError representing what went wrong. Represents an OK or a Successful result. The code succeeded with a value of 'T. Helper type for error handling without exceptions. Choices and Results The type of optional values, represented as structs. Use the constructors ValueSome and ValueNone to create values of this type. Use the values in the ValueOption module to manipulate values of this type, or pattern match against the values directly. Options The representation of "Value of type 'T" The input value. An option representing the value. The representation of "No value" Implicitly converts a value into an optional that is a 'ValueSome' value. The input value The F# compiler ignored this method when determining possible type-directed conversions. Instead, use Some or None explicitly. A voption representing the value. Get the value of a 'ValueSome' option. An InvalidOperationException is raised if the option is 'ValueNone'. Create a value option value that is a 'ValueNone' value. Return 'true' if the value option is a 'ValueSome' value. Return 'true' if the value option is a 'ValueNone' value. Create a value option value that is a 'Some' value. The input value A value option representing the value. The type of optional values, represented as structs. Use the constructors ValueSome and ValueNone to create values of this type. Use the values in the ValueOption module to manipulate values of this type, or pattern match against the values directly. Options The type of optional values. When used from other CLI languages the empty option is the null value. Use the constructors Some and None to create values of this type. Use the values in the Option module to manipulate values of this type, or pattern match against the values directly. 'None' values will appear as the value null to other CLI languages. Instance methods on this type will appear as static methods to other CLI languages due to the use of null as a value representation. Options The representation of "Value of type 'T" The input value. An option representing the value. The representation of "No value" Implicitly converts a value into an optional that is a 'Some' value. The input value The F# compiler ignored this method when determining possible type-directed conversions. Instead, use Some or None explicitly. An option representing the value. Get the value of a 'Some' option. A NullReferenceException is raised if the option is 'None'. Create an option value that is a 'None' value. Return 'true' if the option is a 'Some' value. Return 'true' if the option is a 'None' value. Create an option value that is a 'Some' value. The input value An option representing the value. The type of optional values. When used from other CLI languages the empty option is the null value. Use the constructors Some and None to create values of this type. Use the values in the Option module to manipulate values of this type, or pattern match against the values directly. None values will appear as the value null to other CLI languages. Instance methods on this type will appear as static methods to other CLI languages due to the use of null as a value representation. Options The type of mutable references. Use the functions [!] and [:=] to get and set values of this type. Basic Types The current value of the reference cell The current value of the reference cell The current value of the reference cell The type of mutable references. Use the functions [!] and [:=] to get and set values of this type. Basic Types Convert the given Converter delegate object to an F# function value The input Converter delegate. The F# function. Convert the given Action delegate object to an F# function value The input Action delegate. The F# function. A utility function to convert function values from tupled to curried form The input tupled function. The output curried function. A utility function to convert function values from tupled to curried form The input tupled function. The output curried function. A utility function to convert function values from tupled to curried form The input tupled function. The output curried function. A utility function to convert function values from tupled to curried form The input tupled function. The output curried function. Convert the given Func delegate object to an F# function value The input Func delegate. The F# function. Convert the given Func delegate object to an F# function value The input Func delegate. The F# function. Convert the given Func delegate object to an F# function value The input Func delegate. The F# function. Convert the given Func delegate object to an F# function value The input Func delegate. The F#funcfunction. Convert the given Func delegate object to an F# function value The input Func delegate. The F# function. Convert the given Func delegate object to an F# function value The input Func delegate. The F# function. Convert the given Action delegate object to an F# function value The input Action delegate. The F# function. Convert the given Action delegate object to an F# function value The input Action delegate. The F# function. Convert the given Action delegate object to an F# function value The input Action delegate. The F# function. Convert the given Action delegate object to an F# function value The input Action delegate. The F#funcfunction. Convert the given Action delegate object to an F# function value The input Action delegate. The F# function. Convert the given Action delegate object to an F# function value The input Action delegate. The F# function. Helper functions for converting F# first class function values to and from CLI representations of functions using delegates. Language Primitives Convert an value of type to a F# first class function value The input System.Converter. An F# function of the same type. Convert an F# first class function value to a value of type The input function. A System.Converter of the function type. Convert an F# first class function value to a value of type The input function. System.Converter<'T,'U> Invoke an F# first class function value with two curried arguments. In some cases this will result in a more efficient application than applying the arguments successively. The input function. The first arg. The second arg. The function result. Invoke an F# first class function value with three curried arguments. In some cases this will result in a more efficient application than applying the arguments successively. The input function. The first arg. The second arg. The third arg. The function result. Invoke an F# first class function value with four curried arguments. In some cases this will result in a more efficient application than applying the arguments successively. The input function. The first arg. The second arg. The third arg. The fourth arg. The function result. Invoke an F# first class function value with five curried arguments. In some cases this will result in a more efficient application than applying the arguments successively. The input function. The first arg. The second arg. The third arg. The fourth arg. The fifth arg. The function result. Invoke an F# first class function value with one argument 'U Convert an value of type to a F# first class function value The input System.Converter. An F# function of the same type. Construct an instance of an F# first class function value The created F# function. The CLI type used to represent F# function values. This type is not typically used directly, though may be used from other CLI languages. Language Primitives Specialize the type function at a given type The specialized type. Construct an instance of an F# first class type function value FSharpTypeFunc The CLI type used to represent F# first-class type function values. This type is for use by compiled F# code. Language Primitives Choice 7 of 7 choices Choice 6 of 7 choices Choice 5 of 7 choices Choice 4 of 7 choices Choice 3 of 7 choices Choice 2 of 7 choices Choice 1 of 7 choices Helper types for active patterns with 7 choices. Choices and Results Choice 6 of 6 choices Choice 5 of 6 choices Choice 4 of 6 choices Choice 3 of 6 choices Choice 2 of 6 choices Choice 1 of 6 choices Helper types for active patterns with 6 choices. Choices and Results Choice 5 of 5 choices Choice 4 of 5 choices Choice 3 of 5 choices Choice 2 of 5 choices Choice 1 of 5 choices Helper types for active patterns with 5 choices. Choices and Results Choice 4 of 4 choices Choice 3 of 4 choices Choice 2 of 4 choices Choice 1 of 4 choices Helper types for active patterns with 4 choices. Choices and Results Choice 3 of 3 choices Choice 2 of 3 choices Choice 1 of 3 choices Helper types for active patterns with 3 choices. Choices and Results Choice 2 of 2 choices Choice 1 of 2 choices Helper types for active patterns with 2 choices. Choices and Results Represents a out-argument managed pointer in F# code. This type should only be used with F# 4.5+. ByRef and Pointer Types Represents a in-argument or readonly managed pointer in F# code. This type should only be used with F# 4.5+. ByRef and Pointer Types Represents a managed pointer in F# code. For F# 4.5+ this is considered equivalent to byref<'T, ByRefKinds.InOut> ByRef and Pointer Types Represents a managed pointer in F# code. ByRef and Pointer Types The type of 32-bit unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 8-bit unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 32-bit signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 8-bit signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of single-precision floating point numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of double-precision floating point numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of machine-sized unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 64-bit unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 16-bit unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 8-bit unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 32-bit unsigned integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of machine-sized signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 64-bit signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 16-bit signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 8-bit signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of 32-bit signed integer numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of decimal numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of single-precision floating point numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure The type of double-precision floating point numbers, annotated with a unit of measure. The unit of measure is erased in compiled code and when values of this type are analyzed using reflection. The type is representationally equivalent to . Basic Types with Units of Measure Indicates a function that should be called in a tail recursive way inside its recursive scope. A warning is emitted if the function is analyzed as not tail recursive after the optimization phase. Attributes let mul x y = x * y [<TailCall>] let rec fact n acc = if n = 0 then acc else (fact (n - 1) (mul n acc)) + 23 // warning because of the addition after the call to fact Warning message displayed when the annotated function is used with a value known to be without null Creates an instance of the attribute The message displayed when the annotated function is used with a value known to be without null WarnOnWithoutNullArgumentAttribute When used in a compilation with null-checking enabled, indicates that a function is meant to be used only with potentially-nullable values and warns accordingly. Attributes Creates an instance of the attribute NoCompilerInliningAttribute Indicates a value or a function that must not be inlined by the F# compiler, but may be inlined by the JIT compiler. Attributes Indicates the namespace or module to be automatically opened when an assembly is referenced or an enclosing module opened. Creates an attribute used to mark a namespace or module path to be 'automatically opened' when an assembly is referenced The namespace or module to be automatically opened when an assembly is referenced or an enclosing module opened. AutoOpenAttribute Creates an attribute used to mark a module as 'automatically opened' when the enclosing namespace is opened AutoOpenAttribute Indicates a construct is automatically opened when brought into scope through an assembly reference or then opening of the containing namespace or module. When applied to an assembly, this attribute must be given a string argument, and this indicates a valid module or namespace in that assembly. Source code files compiled with a reference to this assembly are processed in an environment where the given path is automatically opened. When applied to a type or module within an assembly, then the attribute must not be given any arguments, and the type or module is implicitly opened when its enclosing namespace or module is opened. Attributes Creates an instance of the attribute RequireQualifiedAccessAttribute This attribute is used to indicate that references to the elements of a module, record or union type require explicit qualified access. Attributes Creates an instance of the attribute NoDynamicInvocationAttribute This attribute is used to tag values that may not be dynamically invoked at runtime. This is typically added to inlined functions whose implementations include unverifiable code. It causes the method body emitted for the inlined function to raise an exception if dynamically invoked, rather than including the unverifiable code in the generated assembly. Attributes Creates an instance of the attribute UnverifiableAttribute This attribute is used to tag values whose use will result in the generation of unverifiable code. These values are inevitably marked 'inline' to ensure that the unverifiable constructs are not present in the actual code for the F# library, but are rather copied to the source code of the caller. Attributes Indicates if the construct should always be hidden in an editing environment. Indicates if the message should indicate a compiler error. Error numbers less than 10000 are considered reserved for use by the F# compiler and libraries. Indicates the number associated with the message. Indicates the warning message to be emitted when F# source code uses this construct Indicates if the construct should always be hidden in an editing environment. Indicates if the message should indicate a compiler error. Error numbers less than 10000 are considered reserved for use by the F# compiler and libraries. Creates an instance of the attribute. Indicates that a message should be emitted when F# source code uses this construct. Attributes Indicates the text to display by default when objects of this type are displayed using '%A' printf formatting patterns and other two-dimensional text-based display layouts. Creates an instance of the attribute Indicates the text to display when using the '%A' printf formatting. StructuredFormatDisplayAttribute This attribute is used to mark how a type is displayed by default when using '%A' printf formatting patterns and other two-dimensional text-based display layouts. In this version of F# valid values are of the form PreText {PropertyName1} PostText {PropertyName2} ... {PropertyNameX} PostText. The property names indicate properties to evaluate and to display instead of the object itself. Attributes Indicates the number of arguments in each argument group Creates an instance of the attribute Indicates the number of arguments in each argument group. CompilationArgumentCountsAttribute This attribute is generated automatically by the F# compiler to tag functions and members that accept a partial application of some of their arguments and return a residual function. Attributes Creates an instance of the attribute InlineIfLambdaAttribute Adding this attribute to a parameter of function type indicates that, if the overall function or method is inlined and the parameter is determined to be a known lambda, then this function should be statically inlined throughout the body of the function of method. If the function parameter is called multiple times in the implementation of the function or method this attribute may cause code explosion and slow compilation times. Attributes Indicates the warning message to be emitted when F# source code uses this construct Creates an instance of the attribute The warning message to be emitted when code uses this construct. ExperimentalAttribute This attribute is used to tag values that are part of an experimental library feature. Attributes Indicates one or more adjustments to the compiled representation of an F# type or member Creates an instance of the attribute Indicates adjustments to the compiled representation of the type or member. CompilationRepresentationAttribute This attribute is used to adjust the runtime representation for a type. For example, it may be used to note that the null representation may be used for a type. This affects how some constructs are compiled. Attributes Indicates the name of the entity in F# source code Creates an instance of the attribute The name of the method in source. CompilationSourceNameAttribute This attribute is inserted automatically by the F# compiler to tag methods which are given the 'CompiledName' attribute. This attribute is used by the functions in the FSharp.Reflection namespace to reverse-map compiled constructs to their original forms. It is not intended for use from user code. Attributes Indicates the variant number of the entity, if any, in a linear sequence of elements with F# source code Indicates the type definitions needed to resolve the source construct Indicates the relationship between the compiled entity and F# source code Indicates the sequence number of the entity, if any, in a linear sequence of elements with F# source code Indicates the resource the source construct relates to Creates an instance of the attribute Indicates the type definitions needed to resolve the source construct. The name of the resource needed to resolve the source construct. CompilationMappingAttribute Creates an instance of the attribute Indicates the type of source construct. Indicates the index in the sequence of variants. Indicates the index in the sequence of constructs. CompilationMappingAttribute Creates an instance of the attribute Indicates the type of source construct. Indicates the index in the sequence of constructs. CompilationMappingAttribute Creates an instance of the attribute Indicates the type of source construct. CompilationMappingAttribute This attribute is inserted automatically by the F# compiler to tag types and methods in the generated CLI code with flags indicating the correspondence with original source constructs. This attribute is used by the functions in the FSharp.Reflection namespace to reverse-map compiled constructs to their original forms. It is not intended for use from user code. Attributes The release number of the F# version associated with the attribute The minor version number of the F# version associated with the attribute The major version number of the F# version associated with the attribute Creates an instance of the attribute The major version number. The minor version number. The release number. FSharpInterfaceDataVersionAttribute This attribute is added to generated assemblies to indicate the version of the data schema used to encode additional F# specific information in the resource attached to compiled F# libraries. Attributes The value of the attribute, indicating whether the type is automatically marked serializable or not Creates an instance of the attribute Indicates whether the type should be serializable by default. AutoSerializableAttribute Adding this attribute to a type with value 'false' disables the behaviour where F# makes the type Serializable by default. Attributes The name of the value as it appears in compiled code Creates an instance of the attribute The name to use in compiled code. CompiledNameAttribute Adding this attribute to a value or function definition in an F# module changes the name used for the value in compiled CLI code. Attributes Creates an instance of the attribute GeneralizableValueAttribute Adding this attribute to a non-function value with generic parameters indicates that uses of the construct can give rise to generic code through type inference. Attributes Creates an instance of the attribute RequiresExplicitTypeArgumentsAttribute Adding this attribute to a type, value or member requires that uses of the construct must explicitly instantiate any generic type parameters. Attributes Creates an instance of the attribute OptionalArgumentAttribute This attribute is added automatically for all optional arguments. Attributes Indicates if a constraint is asserted that the field type supports 'null' Creates an instance of the attribute Indicates whether to assert that the field type supports null. DefaultValueAttribute Creates an instance of the attribute DefaultValueAttribute Adding this attribute to a field declaration means that the field is not initialized. During type checking a constraint is asserted that the field type supports 'null'. If the 'check' value is false then the constraint is not asserted. Attributes Creates an instance of the attribute NoComparisonAttribute Adding this attribute to a type indicates it is a type where comparison is an abnormal operation. This means that the type does not satisfy the F# 'comparison' constraint. Within the bounds of the F# type system, this helps ensure that the F# generic comparison function is not instantiated directly at this type. The attribute and checking does not constrain the use of comparison with base or child types of this type. Attributes Creates an instance of the attribute CustomComparisonAttribute Adding this attribute to a type indicates it is a type with a user-defined implementation of comparison. Attributes Creates an instance of the attribute CustomEqualityAttribute Adding this attribute to a type indicates it is a type with a user-defined implementation of equality. Attributes Creates an instance of the attribute NoEqualityAttribute Adding this attribute to a type indicates it is a type where equality is an abnormal operation. This means that the type does not satisfy the F# 'equality' constraint. Within the bounds of the F# type system, this helps ensure that the F# generic equality function is not instantiated directly at this type. The attribute and checking does not constrain the use of comparison with base or child types of this type. Attributes Creates an instance of the attribute ProjectionParameterAttribute Indicates that, when a custom operator is used in a computation expression, a parameter is automatically parameterized by the variable space of the computation expression Attributes Indicates if the custom operation maintains the variable space of the query of computation expression through the use of a bind operation Indicates if the custom operation maintains the variable space of the query of computation expression Indicates the name used for the 'on' part of the custom query operator for join-like operators Indicates if the custom operation is an operation similar to a zip in a sequence computation, supporting two inputs Indicates if the custom operation is an operation similar to a join in a sequence computation, supporting two inputs and a correlation constraint Indicates if the custom operation is an operation similar to a group join in a sequence computation, supporting two inputs and a correlation constraint, and generating a group Indicates if the custom operation supports the use of 'into' immediately after the use of the operation in a query or other computation expression to consume the results of the operation Get the name of the custom operation when used in a query or other computation expression Indicates if the custom operation maintains the variable space of the query of computation expression through the use of a bind operation Indicates if the custom operation maintains the variable space of the query of computation expression Indicates the name used for the 'on' part of the custom query operator for join-like operators Indicates if the custom operation is an operation similar to a zip in a sequence computation, supporting two inputs Indicates if the custom operation is an operation similar to a join in a sequence computation, supporting two inputs and a correlation constraint Indicates if the custom operation is an operation similar to a group join in a sequence computation, supporting two inputs and a correlation constraint, and generating a group Indicates if the custom operation supports the use of 'into' immediately after the use of the operation in a query or other computation expression to consume the results of the operation Create an instance of attribute with empty name CustomOperationAttribute Creates an instance of the attribute CustomOperationAttribute Indicates that a member on a computation builder type is a custom query operator, and indicates the name of that operator. Attributes Creates an instance of the attribute StructuralComparisonAttribute Adding this attribute to a record, union, exception, or struct type confirms the automatic generation of implementations for 'System.IComparable' for the type. Attributes Creates an instance of the attribute StructuralEqualityAttribute Adding this attribute to a record, union or struct type confirms the automatic generation of overrides for 'System.Object.Equals(obj)' and 'System.Object.GetHashCode()' for the type. Attributes Creates an instance of the attribute ReferenceEqualityAttribute Adding this attribute to a record or union type disables the automatic generation of overrides for 'System.Object.Equals(obj)', 'System.Object.GetHashCode()' and 'System.IComparable' for the type. The type will by default use reference equality. Attributes Creates an instance of the attribute EntryPointAttribute Adding this attribute to a function indicates it is the entrypoint for an application. If this attribute is not specified for an EXE then the initialization implicit in the module bindings in the last file in the compilation sequence are used as the entrypoint. Attributes Creates an instance of the attribute VolatileFieldAttribute Adding this attribute to an F# mutable binding causes the "volatile" prefix to be used for all accesses to the field. Attributes The value of the attribute, indicating whether the type has a default augmentation or not Creates an instance of the attribute Indicates whether to generate helper members on the CLI class representing a discriminated union. DefaultAugmentationAttribute Adding this attribute to a discriminated union with value false turns off the generation of standard helper member tester, constructor and accessor members for the generated CLI class for that type. Attributes Creates an instance of the attribute CLIMutableAttribute Adding this attribute to a record type causes it to be compiled to a CLI representation with a default constructor with property getters and setters. Attributes Creates an instance of the attribute CLIEventAttribute Adding this attribute to a property with event type causes it to be compiled with as a CLI metadata event, through a syntactic translation to a pair of 'add_EventName' and 'remove_EventName' methods. Attributes Creates an instance of the attribute LiteralAttribute Adding this attribute to a value causes it to be compiled as a CLI constant literal. Attributes The value of the attribute, indicating whether the type allows the null literal or not Creates an instance of the attribute with the specified value AllowNullLiteralAttribute Creates an instance of the attribute AllowNullLiteralAttribute Adding this attribute to a type lets the 'null' literal be used for the type within F# code. This attribute may only be added to F#-defined class or interface types. Attributes Creates an instance of the attribute ClassAttribute Adding this attribute to a type causes it to be represented using a CLI class. Attributes Creates an instance of the attribute InterfaceAttribute Adding this attribute to a type causes it to be represented using a CLI interface. Attributes Creates an instance of the attribute MeasureAnnotatedAbbreviationAttribute Adding this attribute to a type causes it to be interpreted as a refined type, currently limited to measure-parameterized types. This may only be used under very limited conditions. Attributes Creates an instance of the attribute MeasureAttribute Adding this attribute to a type causes it to be interpreted as a unit of measure. This may only be used under very limited conditions. Attributes Creates an instance of the attribute StructAttribute Adding this attribute to a type causes it to be represented using a CLI struct. Attributes Creates an instance of the attribute ComparisonConditionalOnAttribute This attribute is used to indicate a generic container type satisfies the F# 'comparison' constraint only if a generic argument also satisfies this constraint. For example, adding this attribute to parameter 'T on a type definition C<'T> means that a type C<X> only supports comparison if the type X also supports comparison and all other conditions for C<X> to support comparison are also met. The type C<'T> can still be used with other type arguments, but a type such as C<(int -> int)> will not support comparison because the type (int -> int) is an F# function type and does not support comparison. This attribute will be ignored if it is used on the generic parameters of functions or methods. Attributes Creates an instance of the attribute EqualityConditionalOnAttribute This attribute is used to indicate a generic container type satisfies the F# 'equality' constraint only if a generic argument also satisfies this constraint. For example, adding this attribute to parameter 'T on a type definition C<'T> means that a type C<X> only supports equality if the type X also supports equality and all other conditions for C<X> to support equality are also met. The type C<'T> can still be used with other type arguments, but a type such as C<(int -> int)> will not support equality because the type (int -> int) is an F# function type and does not support equality. This attribute will be ignored if it is used on the generic parameters of functions or methods. Attributes The value of the attribute, indicating whether to include the evaluated value of the definition as the outer node of the quotation Creates an instance of the attribute Indicates whether to include the evaluated value of the definition as the outer node of the quotation ReflectedDefinitionAttribute Creates an instance of the attribute ReflectedDefinitionAttribute Adding this attribute to the let-binding for the definition of a top-level value makes the quotation expression that implements the value available for use at runtime. Attributes Creates an instance of the attribute AbstractClassAttribute Adding this attribute to class definition makes it abstract, which means it need not implement all its methods. Instances of abstract classes may not be constructed directly. Attributes The value of the attribute, indicating whether the type is sealed or not. Creates an instance of the attribute Indicates whether the class is sealed. SealedAttribute Creates an instance of the attribute. The created attribute. Adding this attribute to class definition makes it sealed, which means it may not be extended or implemented. Attributes Compile a property as a CLI event. Permit the use of null as a representation for nullary discriminators in a discriminated union. append 'Module' to the end of a module whose name clashes with a type name in the same namespace. Compile a member as 'instance' even if null is used as a representation for this type. Compile an instance member as 'static' . No special compilation representation. Indicates one or more adjustments to the compiled representation of an F# type or member. Attributes Indicates that the compiled entity had private or internal representation in F# source code. The mask of values related to the kind of the compiled entity. Indicates that the compiled entity is part of the representation of an F# value declaration. Indicates that the compiled entity is part of the representation of an F# union case declaration. Indicates that the compiled entity is part of the representation of an F# module declaration. Indicates that the compiled entity is part of the representation of an F# closure. Indicates that the compiled entity is part of the representation of an F# exception declaration. Indicates that the compiled entity is part of the representation of an F# record or union case field declaration. Indicates that the compiled entity is part of the representation of an F# class or other object type declaration. Indicates that the compiled entity is part of the representation of an F# record type declaration. Indicates that the compiled entity is part of the representation of an F# union type declaration. Indicates that the compiled entity has no relationship to an element in F# source code. Indicates the relationship between a compiled entity in a CLI binary and an element in F# source code. Attributes The type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types Basic definitions of operators, options, functions, results, choices, attributes and plain text formatting. The type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types An abbreviation for . Basic Types Type of a formatting expression. Function type generated by printf. Type argument passed to %a formatters Value generated by the overall printf action (e.g. sprint generates a string) Value generated after post processing (e.g. failwithf generates a string internally then raises an exception) Tuple of values generated by scan or match. Language Primitives Type of a formatting expression. Function type generated by printf. Type argument passed to %a formatters Value generated by the overall printf action (e.g. sprint generates a string) Value generated after post processing (e.g. failwithf generates a string internally then raises an exception) Language Primitives Construct a format string The input string. The captured expressions in an interpolated string. The types of expressions for %A expression gaps in interpolated string. The created format string. Construct a format string The input string. The created format string. Type of a formatting expression. Function type generated by printf. Type argument passed to %a formatters Value generated by the overall printf action (e.g. sprint generates a string) Value generated after post processing (e.g. failwithf generates a string internally then raises an exception) Tuple of values generated by scan or match. Language Primitives The raw text of the format string. The captures associated with an interpolated string. The capture types associated with an interpolated string. Construct a format string The input string. The captured expressions in an interpolated string. The types of expressions for %A expression gaps in interpolated string. The PrintfFormat containing the formatted result. Construct a format string The input string. The PrintfFormat containing the formatted result. Type of a formatting expression. Function type generated by printf. Type argument passed to %a formatters Value generated by the overall printf action (e.g. sprint generates a string) Value generated after post processing (e.g. failwithf generates a string internally then raises an exception) Language Primitives Non-exhaustive match failures will raise the MatchFailureException exception Language Primitives maxDegreeOfParallelism must be positive, was {0} This is not a valid query expression. The construct '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. This is not a valid query expression. The property '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. This is not a valid query expression. The method '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression This is not a valid query expression. The following construct was used in a query but is not recognized by the F#-to-LINQ query translator:\n{0}\nCheck the specification of permitted queries and consider moving some of the operations out of the query expression. An if/then/else conditional or pattern matching expression with multiple branches is not permitted in a query. An if/then/else conditional may be used. Unrecognized use of a 'sumBy' or 'averageBy' operator in a query. In queries whose original data is of static type IQueryable, these operators may only be used with result type int32, int64, single, double or decimal 'thenBy' and 'thenByDescending' may only be used with an ordered input The input sequence contains more than one element. The tuple type '{0}' is invalid. Required constructor is not defined. The record type '{0}' is invalid. Required constructor is not defined. A continuation provided by Async.FromContinuations was invoked multiple times The option value was None This value cannot be mutated type argument out of range ill formed expression: AppOp or LetOp Failed to bind assembly '{0}' while processing quotation data Cannot take the address of this quotation Could not bind to method Could not bind property {0} in type {1} Could not bind function {0} in type {1} Bad format specifier (width) Bad format specifier (after {0}) Bad format specifier (precision) Not a function type Missing format specifier The # formatting modifier is invalid in F# Expected a width argument Expected a precision argument Bad integer supplied to dynamic formatter Bad format specifier:{0} Bad float value Multiple CompilationMappingAttributes, expected at most one MoveNext not called, or finished first class uses of '%' or '%%' are not permitted The constructor method '{0}' for the union case could not be found An index satisfying the predicate was not found in the collection. The method '{0}' expects {1} type arguments but {2} were provided Writing a get-only property F# union type requires different number of arguments The tuple lengths are different Tuple access out of range Type mismatch when splicing expression into quotation literal. The type of the expression tree being inserted doesn't match the type expected by the splicing operation. Expected '{0}', but received type '{1}'. Consider type-annotating with the expected expression type, e.g., (%% x : {0}) or (%x : {0}). Type mismatch when building '{0}': function type doesn't match delegate type. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': the expression has the wrong type. Expected '{1}', but received type '{2}'. Receiver object was unexpected, as member is static Reading a set-only property Parent type cannot be null The member is non-static (instance), but no receiver object was supplied Invalid function type Incorrect type Incorrect number of arguments Incorrect instance type Incompatible record length Failed to bind type '{0}' in assembly '{1}' Failed to bind property '{0}' Failed to bind field '{0}' Failed to bind constructor The tuple index '{1}' was out of range for tuple type '{0}'. The System.Threading.SynchronizationContext.Current of the calling thread is null. The step of a range cannot be zero. The step of a range cannot be NaN. The start of a range cannot be NaN. Reset is not supported on this enumerator. The parameter is not a recognized method name. Unexpected quotation hole in expression. Type mismatch when building '{0}': the variable type doesn't match the type of the right-hand-side of a let binding. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': mismatched type of argument and tuple element. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': types of true and false branches differ. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': lower and upper bounds must be integers. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': body of the for loop must be lambda taking integer as an argument. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': invalid parameter for a method or indexer property. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': initializer doesn't match array type. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': incorrect argument type for an F# union. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': incorrect argument type for an F# record. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': guard must return boolean. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': function argument type doesn't match. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': types of expression does not match. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': expression doesn't match the tuple type. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': expected function type in function application or let binding. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': condition expression must be of type bool. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': body must return unit. Expected '{1}', but received type '{2}'. Type mismatch when building '{0}': the type of the field was incorrect. Expected '{1}', but received type '{2}'. Type '{0}' did not have an F# union case named '{1}'. Type '{0}' did not have an F# record field named '{1}'. Not a valid F# union case index. Expected exactly two type arguments. Expected exactly one type argument. The type '{0}' is an F# union type but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. The type '{0}' is an F# record type but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. The type '{0}' is the representation of an F# exception declaration but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. The index is outside the legal range. The object is null and no type was given. Either pass a non-null object or a non-null type parameter. The object is not an F# record value. One of the elements in the array is null. This object is for recursive equality calls and cannot be used for hashing. The input sequence has an insufficient number of elements. The two objects have different types and are not comparable. Type '{0}' is not an F# union type. Type '{0}' is not a tuple type. Type '{0}' is not an F# record type. The function did not compute a permutation. Type '{0}' is not the representation of an F# exception declaration. Type '{0}' is not a function type. Arrays with non-zero base cannot be created on this platform. The static initialization of a file or type resulted in static data being accessed recursively before it was fully initialized. The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized. Negating the minimum value of a twos complement number is invalid. The IAsyncResult object provided does not match this 'End' operation. The IAsyncResult object provided does not match this 'Cancel' operation. Map values cannot be mutated. Mailbox.Scan timed out. Mailbox.Receive timed out. MailboxProcessor.PostAndReply timed out. MailboxProcessor.PostAndAsyncReply timed out. The MailboxProcessor has already been started. The lists had different lengths. The item, key, or index was not found in the collection. This is not a valid tuple type for the F# reflection library. The input sequence was empty. The input must be positive. The input must be non-negative. The input list was empty. The index was outside the range of elements in the list. Failure during generic comparison: the type '{0}' does not implement the System.IComparable interface. This error may be arise from the use of a function such as 'compare', 'max' or 'min' or a data structure such as 'Set' or 'Map' whose keys contain instances of this type. Failed to read enough bytes from the stream. Enumeration based on System.Int32 exceeded System.Int32.MaxValue. Set contains no elements. Enumeration has not started. Call MoveNext. Enumeration already finished. The end of a range cannot be NaN. Dynamic invocation of op_Multiply involving overloading is not supported. Dynamic invocation of op_Multiply involving coercions is not supported. Dynamic invocation of op_Addition involving overloading is not supported. Dynamic invocation of op_Addition involving coercions is not supported. Dynamic invocation of DivideByInt involving coercions is not supported. Expecting delegate type. Input string was not in a correct format. The input array was empty. The arrays have different lengths. First class uses of address-of operators are not permitted. The match cases were incomplete An active pattern to match values of type The input key/value pair. A tuple containing the key and value. let kv = System.Collections.Generic.KeyValuePair(42, "the answer") match kv with // evaluates to "found it" | KeyValue (42, v) -> "found it" | KeyValue (k, v) -> "keep waiting" Converts the argument to character. Numeric inputs are converted according to the UTF-16 encoding for characters. String inputs must be exactly one character long. For other input types the operation requires an appropriate static conversion method on the input type. The input value. The converted char. char "A" // evaluates to 'A' char 0x41 // evaluates to 'A' char 65 // evaluates to 'A' Converts the argument to System.Decimal using a direct conversion for all primitive numeric types. For strings, the input is converted using UInt64.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted decimal. decimal "42.23" // evaluates to 42.23M decimal 0xff // evaluates to 255M decimal -10 // evaluates to -10M Converts the argument to a string using ToString. For standard integer and floating point values and any type that implements IFormattable ToString conversion uses CultureInfo.InvariantCulture. The input value. The converted string. string 'A' // evaluates to "A" string 0xff // evaluates to "255" string -10 // evaluates to "-10" Converts the argument to unsigned native integer using a direct conversion for all primitive numeric types. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted unativeint unativeint 'A' // evaluates to 65un unativeint 0xff // evaluates to 255un unativeint -10 // evaluates to 18446744073709551606un Converts the argument to signed native integer. This is a direct conversion for all primitive numeric types. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted nativeint nativeint 'A' // evaluates to 65n nativeint 0xff // evaluates to 255n nativeint -10 // evaluates to -10n Converts the argument to 64-bit float. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Double.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted float float 'A' // evaluates to 65.0 float 0xff // evaluates to 255.0 float -10 // evaluates to -10.0 Converts the argument to 32-bit float. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Single.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted float32 float32 'A' // evaluates to 65.0f float32 0xff // evaluates to 255.0f float32 -10 // evaluates to -10.0f Converts the argument to unsigned 64-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using UInt64.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted uint64 uint64 'A' // evaluates to 65UL uint64 0xff // evaluates to 255UL uint64 -10 // evaluates to 18446744073709551606UL Converts the argument to signed 64-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Int64.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int64 int64 'A' // evaluates to 65L int64 0xff // evaluates to 255L int64 -10 // evaluates to -10L Converts the argument to unsigned 32-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using UInt32.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted uint32 uint32 'A' // evaluates to 65u uint32 0xff // evaluates to 255u uint32 -10 // evaluates to 4294967286u Converts the argument to signed 32-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Int32.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int32 int32 'A' // evaluates to 65 int32 0xff // evaluates to 255 int32 -10 // evaluates to -10 Converts the argument to a particular enum type. The input value. The converted enum type. type Color = | Red = 1 | Green = 2 | Blue = 3 let c: Color = enum 3 // c evaluates to Blue Converts the argument to an unsigned 32-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using UInt32.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int uint 'A' // evaluates to 65u uint 0xff // evaluates to 255u uint -10 // evaluates to 4294967286u Converts the argument to signed 32-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Int32.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int int 'A' // evaluates to 65 int 0xff // evaluates to 255 int -10 // evaluates to -10 Converts the argument to unsigned 16-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using UInt16.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted uint16 uint16 'A' // evaluates to 65us uint16 0xff // evaluates to 255s uint16 -10 // evaluates to 65526us Converts the argument to signed 16-bit integer. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Int16.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int16 int16 'A' // evaluates to 65s int16 0xff // evaluates to 255s int16 -10 // evaluates to -10s Converts the argument to signed byte. This is a direct conversion for all primitive numeric types. For strings, the input is converted using SByte.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted sbyte sbyte 'A' // evaluates to 65y sbyte 0xff // evaluates to -1y sbyte -10 // evaluates to -10y Converts the argument to byte. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Byte.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted byte byte 'A' // evaluates to 65uy byte 0xff // evaluates to 255uy byte -10 // evaluates to 246uy Overloaded power operator. If n > 0 then equivalent to x*...*x for n occurrences of x. The input base. The input exponent. The base raised to the exponent. pown 2.0 3 // evaluates to 8.0 Overloaded power operator. The input base. The input exponent. The base raised to the exponent. 2.0 ** 3 // evaluates to 8.0 Overloaded truncate operator. The input value. The truncated value. truncate 23.92 // evaluates to 23.0 truncate 23.92f // evaluates to 23.0f Hyperbolic tangent of the given number The input value. The hyperbolic tangent of the input. tanh -1.0 // evaluates to -0.761594156 tanh 0.0 // evaluates to 0.0 tanh 1.0 // evaluates to 0.761594156 Tangent of the given number The input value. The tangent of the input. tan (-0.5 * System.Math.PI) // evaluates to -1.633123935e+16 tan (0.0 * System.Math.PI) // evaluates to 0.0 tan (0.5 * System.Math.PI) // evaluates to 1.633123935e+16 Hyperbolic sine of the given number The input value. The hyperbolic sine of the input. sinh -1.0 // evaluates to -1.175201194 sinh 0.0 // evaluates to 0.0 sinh 1.0 // evaluates to 1.175201194 Sine of the given number The input value. The sine of the input. sin (0.0 * System.Math.PI) // evaluates to 0.0 sin (0.5 * System.Math.PI) // evaluates to 1.0 sin (1.0 * System.Math.PI) // evaluates to 1.224646799e-16 Hyperbolic cosine of the given number The input value. The hyperbolic cosine of the input. cosh -1.0 // evaluates to 1.543080635 cosh 0.0 // evaluates to 1.0 cosh 1.0 // evaluates to 1.543080635 Cosine of the given number The input value. The cosine of the input. cos (0.0 * System.Math.PI) // evaluates to 1.0 cos (0.5 * System.Math.PI) // evaluates to 6.123233996e-17 cos (1.0 * System.Math.PI) // evaluates to -1.0 Square root of the given number The input value. The square root of the input. sqrt 2.0 // Evaluates to 1.414213562 sqrt 100.0 // Evaluates to 10.0 Logarithm to base 10 of the given number The input value. The logarithm to base 10 of the input. log10 1000.0 // Evaluates to 3.0 log10 100000.0 // Evaluates to 5.0 log10 0.0001 // Evaluates to -4.0 log10 -20.0 // Evaluates to nan Natural logarithm of the given number The input value. The natural logarithm of the input. let logBase baseNumber value = (log value) / (log baseNumber) logBase 2.0 32.0 // Evaluates to 5.0 logBase 10.0 1000.0 // Evaluates to 3.0 Round the given number The input value. The nearest integer to the input value. round 3.49 // Evaluates to 3.0 round -3.49 // Evaluates to -3.0 round 3.5 // Evaluates to 4.0 round -3.5 // Evaluates to -4.0 Sign of the given number The input value. -1, 0, or 1 depending on the sign of the input. sign -12.0 // Evaluates to -1 sign 43 // Evaluates to 1 Floor of the given number The input value. The floor of the input. floor 12.1 // Evaluates to 12.0 floor -1.9 // Evaluates to -2.0 Exponential of the given number The input value. The exponential of the input. exp 0.0 // Evaluates to 1.0 exp 1.0 // Evaluates to 2.718281828 exp -1.0 // Evaluates to 0.3678794412 exp 2.0 // Evaluates to 7.389056099 Ceiling of the given number The input value. The ceiling of the input. ceil 12.1 // Evaluates to 13.0 ceil -1.9 // Evaluates to -1.0 Inverse tangent of x/y where x and y are specified separately The y input value. The x input value. The inverse tangent of the input ratio. let angleFromPlaneAtXY x y = atan2 y x * 180.0 / System.Math.PI angleFromPlaneAtXY 0.0 -1.0 // Evaluates to -90.0 angleFromPlaneAtXY 1.0 1.0 // Evaluates to 45.0 angleFromPlaneAtXY -1.0 1.0 // Evaluates to 135.0 Inverse tangent of the given number The input value. The inverse tangent of the input. let angleFrom opposite adjacent = atan(opposite / adjacent) angleFrom 5.0 5.0 // Evaluates to 0.7853981634 Inverse sine of the given number The input value. The inverse sine of the input. let angleFromOpposite opposite hypotenuse = asin(opposite / hypotenuse) angleFromOpposite 6.0 10.0 // Evaluates to 0.6435011088 angleFromOpposite 5.0 3.0 // Evaluates to nan Inverse cosine of the given number The input value. The inverse cosine of the input. let angleFromAdjacent adjacent hypotenuse = acos(adjacent / hypotenuse) angleFromAdjacent 8.0 10.0 // Evaluates to 0.6435011088 Absolute value of the given number. The input value. The absolute value of the input. abs -12 // Evaluates to 12 abs -15.0 // Evaluates to 15.0 A generic hash function. This function has the same behaviour as 'hash', however the default structural hashing for F# union, record and tuple types stops when the given limit of nodes is reached. The exact behaviour of the function can be adjusted on a type-by-type basis by implementing GetHashCode for each type. The limit of nodes. The input object. The computed hash. A generic hash function, designed to return equal hash values for items that are equal according to the "=" operator. By default it will use structural hashing for F# union, record and tuple types, hashing the complete contents of the type. The exact behaviour of the function can be adjusted on a type-by-type basis by implementing GetHashCode for each type. The input object. The computed hash. hash "Bob Jones" // Evaluates to -325251320 Returns the internal size of a type in bytes. For example, sizeof<int> returns 4. sizeof<bool> // Evaluates to 1 sizeof<byte> // Evaluates to 1 sizeof<int> // Evaluates to 4 sizeof<double> // Evaluates to 8 sizeof<struct(byte * byte)> // Evaluates to 2 sizeof<nativeint> // Evaluates to 4 or 8 (32-bit or 64-bit) depending on your platform Generate a System.Type representation for a type definition. If the input type is a generic type instantiation then return the generic type definition associated with all such instantiations. typeof<int list;> // Evaluates to Microsoft.FSharp.Collections.FSharpList`1[System.Int32] typedefof<int list;> // Evaluates to Microsoft.FSharp.Collections.FSharpList`1[T] /// An internal, library-only compiler intrinsic for compile-time generation of a RuntimeMethodHandle. Returns the name of the given symbol. let myVariableName = "This value doesn't matter" nameof(myVariableName) // Evaluates to "myVariableName" Generate a System.Type runtime representation of a static type. let t = typeof<int> // Gets the System.Type t.FullName // Evaluates to "System.Int32" Clean up resources associated with the input object after the completion of the given function. Cleanup occurs even when an exception is raised by the protected code. The resource to be disposed after action is called. The action that accepts the resource. The resulting value. The following code appends 10 lines to test.txt, then closes the StreamWriter when finished. open System.IO using (File.AppendText "test.txt") (fun writer -> for i in 1 .. 10 do writer.WriteLine("Hello World {0}", i)) Execute the function as a mutual-exclusion region using the input value as a lock. The object to be locked. The action to perform during the lock. The resulting value. open System.Linq /// A counter object, supporting unlocked and locked increment type TestCounter () = let mutable count = 0 /// Increment the counter, unlocked member this.IncrementWithoutLock() = count <- count + 1 /// Increment the counter, locked member this.IncrementWithLock() = lock this (fun () -> count <- count + 1) /// Get the count member this.Count = count let counter = TestCounter() // Create a parallel sequence to that uses all our CPUs (seq {1..100000}).AsParallel() .ForAll(fun _ -> counter.IncrementWithoutLock()) // Evaluates to a number between 1-100000, non-deterministically because there is no locking counter.Count let counter2 = TestCounter() // Create a parallel sequence to that uses all our CPUs (seq {1..100000}).AsParallel() .ForAll(fun _ -> counter2.IncrementWithLock()) // Evaluates to 100000 deterministically because the increment to the counter object is locked counter2.Count The standard overloaded skip range operator, e.g. [n..skip..m] for lists, seq {n..skip..m} for sequences The start value of the range. The step value of the range. The end value of the range. The sequence spanning the range using the specified step size. [1..2..6] // Evaluates to [1; 3; 5] [1.1..0.2..1.5] // Evaluates to [1.1; 1.3; 1.5] ['a'..'e'] // Evaluates to ['a'; 'b'; 'c'; 'd'; 'e'] The standard overloaded range operator, e.g. [n..m] for lists, seq {n..m} for sequences The start value of the range. The end value of the range. The sequence spanning the range. [1..4] // Evaluates to [1; 2; 3; 4] [1.5..4.4] // Evaluates to [1.5; 2.5; 3.5] ['a'..'d'] // Evaluates to ['a'; 'b'; 'c'; 'd'] [|1..4|] // Evaluates to an array [|1; 2; 3; 4|] { 1..4 } // Evaluates to a sequence [1; 2; 3; 4]) Reads the value of the property . Reads the value of the property . Reads the value of the property . Equivalent to Equivalent to Equivalent to Equivalent to Exit the current hardware isolated process, if security settings permit, otherwise raise an exception. Calls . The exit code to use. Never returns. [<EntryPoint>] let main argv = if argv.Length = 0 then eprintfn "You must provide arguments" exit(-1) // Causes program to quit with an error code printfn "Argument count: %i" argv.Length 0 Builds a sequence using sequence expression syntax The input sequence. The result sequence. seq { for i in 0..10 do yield (i, i*i) } Negate a logical value. Not True equals False and not False equals True The value to negate. The result of the negation. not (2 + 2 = 5) // Evaluates to true // not is a function that can be compose with other functions let fileDoesNotExist = System.IO.File.Exists >> not Concatenate two lists. The first list. The second list. The concatenation of the lists. let l1 = ['a'; 'b'; 'c'] let l2 = ['d'; 'e'; 'f'] l1 @ l2 // Evaluates to ['a'; 'b'; 'c'; 'd'; 'e'; 'f'] Increment a mutable reference cell containing an integer The reference cell. let count = ref 99 // Creates a reference cell object with a mutable Value property incr count // Increments our counter count.Value // Evaluates to 100 Decrement a mutable reference cell containing an integer The reference cell. let count = ref 99 // Creates a reference cell object with a mutable Value property decr count // Decrements our counter count.Value // Evaluates to 98 Dereference a mutable reference cell The cell to dereference. The value contained in the cell. let count = ref 12 // Creates a reference cell object with a mutable Value property count.Value // Evaluates to 12 !count // Also evaluates to 12 (with shorter syntax) Assign to a mutable reference cell The cell to mutate. The value to set inside the cell. let count = ref 0 // Creates a reference cell object with a mutable Value property count.Value <- 1 // Updates the value count := 2 // Also updates the value, but with shorter syntax count.Value // Evaluates to 2 Create a mutable reference cell The value to contain in the cell. The created reference cell. let count = ref 0 // Creates a reference cell object with a mutable Value property count.Value // Evaluates to 0 count.Value <- 1 // Updates the value count.Value // Evaluates to 1 The identity function The input value. The same value. id 12 // Evaluates to 12 id "abc" // Evaluates to "abc" Throw a exception The exception message. The result value. type FileReader(fileName: string) = let mutable isOpen = false member this.Open() = if isOpen then invalidOp "File is already open" // ... Here we may open the file ... isOpen <- true let reader = FileReader("journal.txt") reader.Open() // Executes fine reader.Open() // Throws System.InvalidOperationException: File is already open Throw a System.ArgumentNullException if the given value is null exception The argument name. The result value. Throw a exception The argument name. Never returns. let fullName firstName lastName = if isNull firstName then nullArg (nameof(firstName)) if isNull lastName then nullArg (nameof(lastName)) firstName + " " + lastName fullName null "Jones" // Throws System.ArgumentNullException: Value cannot be null. (Parameter 'firstName') Throw a exception with the given argument name and message. The argument name. The exception message. Never returns. let fullName firstName lastName = if String.IsNullOrWhiteSpace(firstName) then invalidArg (nameof(firstName)) "First name can't be null or blank" if String.IsNullOrWhiteSpace(lastName) then invalidArg (nameof(lastName)) "Last name can't be null or blank" firstName + " " + lastName fullName null "Jones" Throws System.ArgumentException: First name can't be null or blank (Parameter 'firstName') Throw a exception. The exception message. Never returns. let failingFunction() = failwith "Oh no" // Throws an exception true // Never reaches this failingFunction() // Throws a System.Exception Wraps a value type into System.Nullable In a future revision of nullness support this may be unified with 'withNull'. The value to wrap. System.Nullable wrapper of the input argument. Re-types a value into a nullable reference type (|null) The non-nullable value. The same value re-typed as a nullable reference type. Asserts that the value is non-null. In a future revision of nullness support this may be unified with 'nonNull'. The value to check. True when value is null, false otherwise. Asserts that the value is non-null. The value to check. The value when it is not null. If the value is null an exception is raised. Get the null value for a value type. In a future revision of nullness support this may be unified with 'null'. The null value for a value type. Determines whether the given value is not null. The value to check. True when value is not null, false otherwise. Determines whether the given value is null. In a future revision of nullness support this may be unified with 'isNull'. The value to check. True when value is null, false otherwise. When used in a pattern checks the given value is not null. In a future revision of nullness support this may be unified with 'NonNullQuick'. The value to check. The non-null value. When used in a pattern checks the given value is not null. The value to check. The non-null value. Determines whether the given value is null. In a future revision of nullness support this may be unified with 'Null|NonNull'. The value to check. A choice indicating whether the value is null or not-null. Determines whether the given value is null. The value to check. A choice indicating whether the value is null or not-null. Determines whether the given value is null. The value to check. True when value is null, false otherwise. isNull null // Evaluates to true isNull "Not null" // Evaluates to false Try to unbox a strongly typed value. The boxed value. The unboxed result as an option. let x: int = 123 let obj1 = box x // obj1 is a generic object type tryUnbox<int> obj1 // Evaluates to Some(123) tryUnbox<double> obj1 // Evaluates to None Boxes a strongly typed value. The value to box. The boxed object. let x: int = 123 let obj1 = box x // obj1 is a generic object type unbox<int> obj1 // Evaluates to 123 (int) unbox<double> obj1 // Throws System.InvalidCastException Unbox a strongly typed value. The boxed value. The unboxed result. let x: int = 123 let obj1 = box x // obj1 is a generic object type unbox<int> obj1 // Evaluates to 123 (int) unbox<double> obj1 // Throws System.InvalidCastException Ignore the passed value. This is often used to throw away results of a computation. The value to ignore. ignore 55555 // Evaluates to () Minimum based on generic comparison The first value. The second value. The minimum value. min 1 2 // Evaluates to 1 min [1;2;3] [1;2;4] // Evaluates to [1;2;3] min "zoo" "alpha" // Evaluates to "alpha" Maximum based on generic comparison The first value. The second value. The maximum value. max 1 2 // Evaluates to 2 max [1;2;3] [1;2;4] // Evaluates to [1;2;4] max "zoo" "alpha" // Evaluates to "zoo" Generic comparison. The first value. The second value. The result of the comparison. compare 1 2 // Evaluates to -1 compare [1;2;3] [1;2;4] // Evaluates to -1 compare 2 2 // Evaluates to 0 compare [1;2;3] [1;2;3] // Evaluates to 0 compare 2 1 // Evaluates to 1 compare [1;2;4] [1;2;3] // Evaluates to 1 Return the second element of a tuple, snd (a,b) = b. The input tuple. The second value. snd ("first", 2) // Evaluates to 2 Return the first element of a tuple, fst (a,b) = a. The input tuple. The first value. fst ("first", 2) // Evaluates to "first" Matches objects whose runtime type is precisely The input exception. A string option. Builds a object. The message for the Exception. A System.Exception. let throwException() = raise(Failure("Oh no!!!")) true // Never gets here throwException() // Throws a generic Exception class Rethrows an exception. This should only be used when handling an exception The result value. let readFile (fileName: string) = try File.ReadAllText(fileName) with ex -> eprintfn "Couldn't read %s" fileName reraise() readFile "/this-file-doest-exist" // Prints the message to stderr // Throws a System.IO.FileNotFoundException Rethrows an exception. This should only be used when handling an exception The result value. Raises an exception The exception to raise. The result value. open System.IO exception FileNotFoundException of string let readFile (fileName: string) = if not (File.Exists(fileName)) then raise(FileNotFoundException(fileName)) File.ReadAllText(fileName) readFile "/this-file-doest-exist" When executed, raises a FileNotFoundException. Concatenate two strings. The operator '+' may also be used. Used to specify a default value for an optional argument in the implementation of a function A value option representing the argument. The default value of the argument. The argument value. If it is None, the defaultValue is returned. let arg1 = ValueSome(5) defaultValueArg arg1 6 // Evaluates to 5 defaultValueArg ValueNone 6 // Evaluates to 6 Used to specify a default value for an optional argument in the implementation of a function An option representing the argument. The default value of the argument. The argument value. If it is None, the defaultValue is returned. type Vector(x: double, y: double, ?z: double) = let z = defaultArg z 0.0 member this.X = x member this.Y = y member this.Z = z let v1 = Vector(1.0, 2.0) v1.Z // Evaluates to 0. let v2 = Vector(1.0, 2.0, 3.0) v2.Z // Evaluates to 3.0 Used to specify a default value for an nullable value argument in the implementation of a function The default value of the argument. A nullable value representing the argument. The argument value. If it is null, the defaultValue is returned. Used to specify a default value for a nullable reference argument in the implementation of a function The default value of the argument. A nullable value representing the argument. The argument value. If it is null, the defaultValue is returned. Apply a function to three values, the values being a triple on the right, the function on the left The function. The first argument. The second argument. The third argument. The function result. let sum3 x y z = x + y + z sum3 <||| (3, 4, 5) // Evaluates to 12 Apply a function to two values, the values being a pair on the right, the function on the left The function. The first argument. The second argument. The function result. let sum x y = x + y sum <|| (3, 4) // Evaluates to 7 Apply a function to a value, the value being on the right, the function on the left The function. The argument. The function result. let doubleIt x = x * 2 doubleIt <| 3 // Evaluates to 6 Apply a function to three values, the values being a triple on the left, the function on the right The first argument. The second argument. The third argument. The function. The function result. let sum3 x y z = x + y + z (3, 4, 5) |||> sum3 // Evaluates to 12 Apply a function to two values, the values being a pair on the left, the function on the right The first argument. The second argument. The function. The function result. let sum x y = x + y (3, 4) ||> sum // Evaluates to 7 Apply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6 Compose two functions, the function on the right being applied first The second function to apply. The first function to apply. The composition of the input functions. let addOne x = x + 1 let doubleIt x = x * 2 let doubleThenAdd = addOne << doubleIt doubleThenAdd 3 Compose two functions, the function on the left being applied first The first function to apply. The second function to apply. The composition of the input functions. let addOne x = x + 1 let doubleIt x = x * 2 let addThenDouble = addOne >> doubleIt addThenDouble 3 // Evaluates to 8 Structural inequality The first parameter. The second parameter. The result of the comparison. 5 <> 5 // Evaluates to false 5 <> 6 // Evaluates to true [1; 2] <> [1; 2] // Evaluates to false Structural equality The first parameter. The second parameter. The result of the comparison. 5 = 5 // Evaluates to true 5 = 6 // Evaluates to false [1; 2] = [1; 2] // Evaluates to true (1, 5) = (1, 6) // Evaluates to false Structural less-than-or-equal comparison The first parameter. The second parameter. The result of the comparison. 5 <= 1 // Evaluates to false 5 <= 5 // Evaluates to true [1; 5] <= [1; 6] // Evaluates to true Structural greater-than-or-equal The first parameter. The second parameter. The result of the comparison. 5 >= 1 // Evaluates to true 5 >= 5 // Evaluates to true [1; 5] >= [1; 6] // Evaluates to false Structural greater-than The first parameter. The second parameter. The result of the comparison. 5 > 1 // Evaluates to true 5 > 5 // Evaluates to false (1, "a") > (1, "z") // Evaluates to false Structural less-than comparison The first parameter. The second parameter. The result of the comparison. 1 < 5 // Evaluates to true 5 < 5 // Evaluates to false (1, "a") < (1, "z") // Evaluates to true Overloaded prefix-plus operator The input value. The result of the operation. Overloaded bitwise-NOT operator The input value. The result of the operation. let byte1 = 60uy // 00111100 let byte2 = ~~~b1 // 11000011 Evaluates to 195 Overloaded byte-shift right operator by a specified number of bits The input value. The amount to shift. The result of the operation. let a = 206 // 00000000000000000000000011010000 let c1 = a >>> 2 // 00000000000000000000000000110100 // Evaluates to 51 let c2 = a >>> 6 // 00000000000000000000000000000011 Evaluates to 3 Overloaded byte-shift left operator by a specified number of bits The input value. The amount to shift. The result of the operation. let a = 13 // 00000000000000000000000000001101 let c = a <<< 4 // 00000000000000000000000011010000 Evaluates to 208 Overloaded bitwise-XOR operator The first parameter. The second parameter. The result of the operation. let a = 13 // 00000000000000000000000000001101 let b = 11 // 00000000000000000000000000001011 let c = a ^^^ b // 00000000000000000000000000000110 Evaluates to 6 Overloaded bitwise-OR operator The first parameter. The second parameter. The result of the operation. let a = 13 // 00000000000000000000000000001101 let b = 11 // 00000000000000000000000000001011 let c = a ||| b // 00000000000000000000000000001111 Evaluates to 15 Overloaded bitwise-AND operator The first parameter. The second parameter. The result of the operation. let a = 13 // 00000000000000000000000000001101 let b = 11 // 00000000000000000000000000001011 let c = a &&& b // 00000000000000000000000000001001 Evaluates to 9 Overloaded modulo operator The first parameter. The second parameter. The result of the operation. 29 % 5 // Evaluates to 4 Overloaded division operator The first parameter. The second parameter. The result of the operation. 16 / 2 // Evaluates to 8 Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48 Overloaded subtraction operator The first parameter. The second parameter. The result of the operation. 10 - 2 // Evaluates to 8 Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "World" // Evaluates to "Hello World" Overloaded unary negation. The value to negate. The result of the operation. Converts the argument to char. Numeric inputs are converted using a checked conversion according to the UTF-16 encoding for characters. String inputs must be exactly one character long. For other input types the operation requires an appropriate static conversion method on the input type. The input value. The converted char Converts the argument to unativeint. This is a direct, checked conversion for all primitive numeric types. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted unativeint Converts the argument to . This is a direct, checked conversion for all primitive numeric types. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted nativeint Converts the argument to uint64. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted uint64 Converts the argument to int64. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int64 Converts the argument to uint32. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted uint32 Converts the argument to int32. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int32 Converts the argument to int. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int Converts the argument to uint16. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted uint16 Converts the argument to int16. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted int16 Converts the argument to sbyte. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted sbyte Converts the argument to byte. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted byte Overloaded multiplication operator (checks for overflow) The first value. The second value. The product of the two input values. Overloaded addition operator (checks for overflow) The first value. The second value. The sum of the two input values. Overloaded subtraction operator (checks for overflow) The first value. The second value. The first value minus the second value. Overloaded unary negation (checks for overflow) The input value. The negated value. This module contains the basic arithmetic operations with overflow checks. Calls GetHashCode() on the value The value. The hash code. Minimum of the two values The first value. The second value. The minimum value. Maximum of the two values The first value. The second value. The maximum value. Compares the two values The first value. The second value. The result of the comparison. Compares the two values for inequality The first parameter. The second parameter. The result of the comparison. Compares the two values for equality The first parameter. The second parameter. The result of the comparison. Compares the two values for less-than-or-equal The first parameter. The second parameter. The result of the comparison. Compares the two values for greater-than-or-equal The first parameter. The second parameter. The result of the comparison. Compares the two values for greater-than The first parameter. The second parameter. The result of the comparison. Compares the two values for less-than The first parameter. The second parameter. The result of the comparison. A module of comparison and equality operators that are statically resolved, but which are not fully generic and do not make structural comparison. Opening this module may make code that relies on structural or generic comparison no longer compile. When used in a pattern forgets 'nullness' of the value without any runtime check. This is an unsafe operation, as null check is being skipped and null value can be returned. The value to retype from ('T | null) to 'T . The non-null value. Unsafely retypes the value from ('T | null) to 'T without doing any null check at runtime. This is an unsafe operation. The possibly nullable value. The same value as in the input. Perform generic hashing on a value where the type of the value is not statically required to satisfy the 'equality' constraint. The computed hash value. Perform generic equality on two values where the type of the values is not statically required to satisfy the 'equality' constraint. The result of the comparison. Perform generic comparison on two values where the type of the values is not statically required to have the 'comparison' constraint. The result of the comparison. Generate a default value for any type. This is null for reference types, For structs, this is struct value where all fields have the default value. This function is unsafe in the sense that some F# values do not have proper null values. Unboxes a strongly typed value. This is the inverse of box, unbox<t>(box<t> a) equals a. The boxed value. The unboxed result. This module contains basic operations which do not apply runtime and/or static checks This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'decimal' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'float' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'float32' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'unativeint' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'nativeint' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'uint64' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'int64' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'uint32' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'int32' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'uint16' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'int16' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'sbyte' This is a library intrinsic. Calls to this function may be generated by uses of the generic 'pown' operator on values of type 'byte' This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. This is a library intrinsic. Calls to this function may be generated by evaluating quotations. Generate a range of values using the given zero, add, start, step and stop values Generate a range of values using the given zero, add, start, step and stop values Generate a range of char values Generate a range of byte values Generate a range of sbyte values Generate a range of uint16 values Generate a range of int16 values Generate a range of unativeint values Generate a range of nativeint values Generate a range of uint32 values Generate a range of uint64 values Generate a range of int64 values Generate a range of float32 values Generate a range of float values Generate a range of integers Gets a slice from a string The source string. The index of the first character of the slice. The index of the last character of the slice. The substring from the given indices. Sets a slice of an array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 1D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 1D slice of a 4D array The target array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 1D slice of a 4D array The target array. The fixed index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 1D slice of a 4D array The target array. The fixed index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 2D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 2D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 2D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 2D slice of a 4D array The target array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 2D slice of a 4D array The target array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 2D slice of a 4D array The target array. The fixed index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 3D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The source array. Sets a 3D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 3D slice of a 4D array The target array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Sets a 3D slice of a 4D array The target array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The source array. Gets a 1D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The fixed index of the fourth dimension. The one dimensional sub array from the given indices. Gets a 1D slice of a 4D array The source array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The fixed index of the fourth dimension. The one dimensional sub array from the given indices. Gets a 1D slice of a 4D array The source array. The fixed index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The one dimensional sub array from the given indices. Gets a 1D slice of a 4D array The source array. The fixed index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The one dimensional sub array from the given indices. Gets a 2D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The fixed index of the fourth dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 4D array The source array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 4D array The source array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 4D array The source array. The fixed index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The two dimensional sub array from the given indices. Gets a 3D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The fixed index of the fourth dimension. The three dimensional sub array from the given indices. Gets a 3D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The three dimensional sub array from the given indices. Gets a 3D slice of a 4D array The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The three dimensional sub array from the given indices. Gets a 3D slice of a 4D array The source array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The three dimensional sub array from the given indices. Gets a slice of an array The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The start index of the fourth dimension. The end index of the fourth dimension. The four dimensional sub array from the given indices. Sets a 1D slice of a 3D array. The target array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The source array. The one dimensional sub array from the given indices. Sets a 1D slice of a 3D array. The target array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The source array. The one dimensional sub array from the given indices. Sets a 1D slice of a 3D array. The target array. The fixed index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The source array. The one dimensional sub array from the given indices. Sets a 2D slice of a 3D array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The source array. The two dimensional sub array from the given indices. Sets a 2D slice of a 3D array The target array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The source array. The two dimensional sub array from the given indices. Sets a 2D slice of a 3D array The target array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The source array. The two dimensional sub array from the given indices. Sets a slice of an array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The source array. Gets a 1D slice of a 3D array. The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The fixed index of the third dimension. The one dimensional sub array from the given indices. Gets a 1D slice of a 3D array. The source array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The one dimensional sub array from the given indices. Gets a 1D slice of a 3D array. The source array. The fixed index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The one dimensional sub array from the given indices. Gets a 2D slice of a 3D array. The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The fixed index of the third dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 3D array. The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The start index of the third dimension. The end index of the third dimension. The two dimensional sub array from the given indices. Gets a 2D slice of a 3D array. The source array. The fixed index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The two dimensional sub array from the given indices. Gets a slice of an array The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The start index of the third dimension. The end index of the third dimension. The three dimensional sub array from the given indices. Sets a vector slice of a 2D array. The index of the second dimension is fixed. The target array. The start index of the first dimension. The end index of the first dimension. The index of the second dimension. The source array. Sets a vector slice of a 2D array. The index of the first dimension is fixed. The target array. The index of the first dimension. The start index of the second dimension. The end index of the second dimension. The source array. Sets a region slice of an array The target array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The source array. Gets a vector slice of a 2D array. The index of the second dimension is fixed. The source array. The start index of the first dimension. The end index of the first dimension. The fixed index of the second dimension. The sub array from the input indices. Gets a vector slice of a 2D array. The index of the first dimension is fixed. The source array. The index of the first dimension. The start index of the second dimension. The end index of the second dimension. The sub array from the input indices. Gets a region slice of an array The source array. The start index of the first dimension. The end index of the first dimension. The start index of the second dimension. The end index of the second dimension. The two dimensional sub array from the input indices. Sets a slice of an array The target array. The start index. The end index. The source array. Gets a slice of an array The input array. The start index. The end index. The sub array from the input indices. A module of compiler intrinsic functions for efficient implementations of F# integer ranges and dynamic invocations of other F# operators Get the index for the element offset elements away from the end of the collection. The rank of the index. The offset from the end. The corresponding index from the start. Get the index for the element offset elements away from the end of the collection. The rank of the index. The offset from the end. The corresponding index from the start. Get the index for the element offset elements away from the end of the collection. The rank of the index. This refers to the dimension in the 2d array. The offset from the end. The corresponding index from the start. Get the index for the element offset elements away from the end of the collection. The rank of the index. This refers to the dimension in the 3d array. The offset from the end. The corresponding index from the start. Get the index for the element offset elements away from the end of the collection. The rank of the index. This refers to the dimension in the 4d array. The offset from the end. The corresponding index from the start. Contains extension methods to allow the use of F# indexer notation with arrays. This module is automatically opened in all F# code. Basic F# Operators. This module is automatically opened in all F# code. Basic Operators Invoke an F# first class function value that accepts five curried arguments without intervening execution The first arg. The second arg. The third arg. The fourth arg. The fifth arg. The function result. Adapt an F# first class function value to be an optimized function value that can accept five curried arguments without intervening execution. The input function. The optimized function. Construct an optimized function value that can accept five curried arguments without intervening execution. The optimized function. The CLI type used to represent F# function values that accept five curried arguments without intervening execution. This type should not typically used directly from either F# code or from other CLI languages. Invoke an F# first class function value that accepts four curried arguments without intervening execution The first arg. The second arg. The third arg. The fourth arg. The function result. Adapt an F# first class function value to be an optimized function value that can accept four curried arguments without intervening execution. The input function. The optimized function. Construct an optimized function value that can accept four curried arguments without intervening execution. The optimized function. The CLI type used to represent F# function values that accept four curried arguments without intervening execution. This type should not typically used directly from either F# code or from other CLI languages. Invoke an F# first class function value that accepts three curried arguments without intervening execution The first arg. The second arg. The third arg. The function result. Adapt an F# first class function value to be an optimized function value that can accept three curried arguments without intervening execution. The input function. The adapted function. Construct an optimized function value that can accept three curried arguments without intervening execution. The optimized function. The CLI type used to represent F# function values that accept three iterated (curried) arguments without intervening execution. This type should not typically used directly from either F# code or from other CLI languages. Invoke the optimized function value with two curried arguments The first arg. The second arg. The function result. Adapt an F# first class function value to be an optimized function value that can accept two curried arguments without intervening execution. The input function. The adapted function. Construct an optimized function value that can accept two curried arguments without intervening execution. The optimized function. The CLI type used to represent F# function values that accept two iterated (curried) arguments without intervening execution. This type should not typically used directly from either F# code or from other CLI languages. An implementation module used to hold some private implementations of function value invocation. Language Primitives Divides a value by an integer. The input value. The input int. The division result. Resolves to the value 'one' for any primitive numeric type or any type with a static member called 'One' Resolves to the zero value for any primitive numeric type or any type with a static member called 'Zero' A compiler intrinsic that implements dynamic invocations for the DivideByInt primitive. A compiler intrinsic that implements dynamic invocations related to the '=' operator. A compiler intrinsic that implements dynamic invocations related to the '=' operator. A compiler intrinsic that implements dynamic invocations related to the '>=' operator. A compiler intrinsic that implements dynamic invocations related to the '<=' operator. A compiler intrinsic that implements dynamic invocations related to the '>' operator. A compiler intrinsic that implements dynamic invocations related to the '<' operator. A compiler intrinsic that implements dynamic invocations related to checked conversion operators. A compiler intrinsic that implements dynamic invocations related to conversion operators. A compiler intrinsic that implements dynamic invocations related to the '~~~' operator. A compiler intrinsic that implements dynamic invocations related to the '^^^' operator. A compiler intrinsic that implements dynamic invocations to the '|||' operator. A compiler intrinsic that implements dynamic invocations to the '&&&' operator. A compiler intrinsic that implements dynamic invocations to the '>>>' operator. A compiler intrinsic that implements dynamic invocations to the '<<<' operator. A compiler intrinsic that implements dynamic invocations to the checked unary '-' operator. A compiler intrinsic that implements dynamic invocations to the checked '-' operator. A compiler intrinsic that implements dynamic invocations to the '%' operator. A compiler intrinsic that implements dynamic invocations to the unary '-' operator. A compiler intrinsic that implements dynamic invocations to the '/' operator. A compiler intrinsic that implements dynamic invocations to the '-' operator. A compiler intrinsic that implements dynamic invocations to the checked '*' operator. A compiler intrinsic that implements dynamic invocations to the '*' operator. A compiler intrinsic that implements dynamic invocations to the checked '+' operator. A compiler intrinsic that implements dynamic invocations to the '+' operator. Resolves to the value 'one' for any primitive numeric type or any type with a static member called 'One'. Resolves to the zero value for any primitive numeric type or any type with a static member called 'Zero'. Parse an uint64 according to the rules used by the overloaded 'uint64' conversion operator when applied to strings The input string. The parsed value. Parse an int64 according to the rules used by the overloaded 'int64' conversion operator when applied to strings The input string. The parsed value. Parse an uint32 according to the rules used by the overloaded 'uint32' conversion operator when applied to strings The input string. The parsed value. Parse an int32 according to the rules used by the overloaded 'int32' conversion operator when applied to strings The input string. The parsed value. Creates a unativeint value with units-of-measure The input unativeint. The unativeint with units-of-measure. Creates a byte value with units-of-measure The input byte. The byte with units-of-measure. Creates a uint16 value with units-of-measure The input uint16. The uint16 with units-of-measure. Creates a uint64 value with units-of-measure The input uint64. The uint64 with units-of-measure. Creates a uint value with units-of-measure The input uint. The uint with units-of-measure. Creates a nativeint value with units-of-measure The input nativeint. The nativeint with units-of-measure. Creates an sbyte value with units-of-measure The input sbyte. The sbyte with units-of-measure. Creates an int16 value with units-of-measure The input int16. The int16 with units-of-measure. Creates an int64 value with units-of-measure The input int64. The int64 with units of measure. Creates an int32 value with units-of-measure The input int. The int with units of measure. Creates a decimal value with units-of-measure The input decimal. The decimal with units of measure. Creates a float32 value with units-of-measure The input float. The float with units-of-measure. Creates a float value with units-of-measure The input float. The float with units-of-measure. Get the underlying value for an enum value The input enum. The enumeration as a value. Build an enum value from an underlying value The input value. The value as an enumeration. Recursively hash a part of a value according to its structure. The comparison function. The input object. The hashed value. Hash a value according to its structure. Use the given limit to restrict the hash when hashing F# records, lists and union types. The limit on the number of nodes. The input object. The hashed value. Hash a value according to its structure. This hash is not limited by an overall node count when hashing F# records, lists and union types. The input object. The hashed value. Make an F# comparer object for the given type Make an F# hash/equality object for the given type Make an F# hash/equality object for the given type using node-limited hashing when hashing F# records, lists and union types. The input limit on the number of nodes. System.Collections.Generic.IEqualityComparer<'T> Make an F# hash/equality object for the given type Make an F# comparer object for the given type, where it can be null if System.Collections.Generic.Comparer<'T>.Default Make an F# comparer object for the given type A static F# comparer object Return an F# comparer object suitable for hashing and equality. This hashing behaviour of the returned comparer is not limited by an overall node count when hashing F# records, lists and union types. This equality comparer has equivalence relation semantics ([nan] = [nan]). Return an F# comparer object suitable for hashing and equality. This hashing behaviour of the returned comparer is not limited by an overall node count when hashing F# records, lists and union types. The physical hash. Hashes on the object identity. The input object. The hashed value. Reference/physical equality. True if the inputs are reference-equal, false otherwise. The first value. The second value. The result of the comparison. Take the maximum of two values structurally according to the order given by GenericComparison The first value. The second value. The maximum value. Take the minimum of two values structurally according to the order given by GenericComparison The first value. The second value. The minimum value. Compare two values The first value. The second value. The result of the comparison. Compare two values The first value. The second value. The result of the comparison. Compare two values The first value. The second value. The result of the comparison. Compare two values The first value. The second value. The result of the comparison. Compare two values. May be called as a recursive case from an implementation of System.IComparable to ensure consistent NaN comparison semantics. The function to compare the values. The first value. The second value. The result of the comparison. Compare two values The first value. The second value. The result of the comparison. Compare two values for equality The first value. The second value. The result of the comparison. Compare two values for equality using equivalence relation semantics ([nan] = [nan]) The first value. The second value. The result of the comparison. Compare two values for equality using partial equivalence relation semantics ([nan] <> [nan]) The first value. The second value. The result of the comparison. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. A primitive entry point used by the F# compiler for optimization purposes. The F# compiler emits calls to some of the functions in this module as part of the compiled form of some language constructs The standard overloaded associative (4-indexed) mutation operator The standard overloaded associative (3-indexed) mutation operator The standard overloaded associative (2-indexed) mutation operator The standard overloaded associative (indexed) mutation operator The standard overloaded associative (4-indexed) lookup operator The standard overloaded associative (3-indexed) lookup operator The standard overloaded associative (2-indexed) lookup operator The standard overloaded associative (indexed) lookup operator A compiler intrinsic for checking initialization soundness of recursive bindings A compiler intrinsic for checking initialization soundness of recursive static bindings A compiler intrinsic for checking initialization soundness of recursive bindings A compiler intrinsic for the efficient compilation of sequence expressions This function implements parsing of decimal constants This function implements calls to default constructors accessed by 'new' constraints. Primitive used by pattern match compilation A compiler intrinsic that implements the ':?' operator A compiler intrinsic that implements the ':?' operator A compiler intrinsic that implements the ':?>' operator A compiler intrinsic that implements the ':?>' operator The F# compiler emits calls to some of the functions in this module as part of the compiled form of some language constructs Address-of. Uses of this value may result in the generation of unverifiable code. The input object. The unmanaged pointer. Address-of. Uses of this value may result in the generation of unverifiable code. The input object. The managed pointer. Binary 'or'. When used as a binary operator the right hand value is evaluated only on demand The first value. The second value. The result of the operation. Binary 'or'. When used as a binary operator the right hand value is evaluated only on demand. Binary 'and'. When used as a binary operator the right hand value is evaluated only on demand The first value. The second value. The result of the operation. Binary 'and'. When used as a binary operator the right hand value is evaluated only on demand. The F# compiler emits calls to some of the functions in this module as part of the compiled form of some language constructs For compiler use only Language primitives associated with the F# language Language Primitives Represents a byref that can be both read and written Represents a byref that can be read Represents a byref that can be written Represents the types of byrefs in F# 4.5+ ByRef and Pointer Types Convert a value option to an option. The input value option. The resulting option. ValueSome 42 |> ValueOption.toOption // evaluates to Some 42 (ValueNone: int voption) |> ValueOption.toOption // evaluates to None Convert an option to a value option. The input option. The resulting value option. Some 42 |> ValueOption.ofOption // evaluates to ValueSome 42 (None: int option) |> ValueOption.ofOption // evaluates to ValueNone Convert an option to a potentially null value. The input value. The result value, which is null if the input was ValueNone. (ValueNone: string ValueOption) |> ValueOption.toObj // evaluates to null ValueSome "not a null string" |> ValueOption.toObj // evaluates to "not a null string" Convert a potentially null value to a value option. The input value. The result value option. (null: string) |> ValueOption.ofObj // evaluates to ValueNone "not a null string" |> ValueOption.ofObj // evaluates to (ValueSome "not a null string") Convert a Nullable value to a value option. The input nullable value. The result value option. System.Nullable<int>() |> ValueOption.ofNullable // evaluates to ValueNone System.Nullable(42) |> ValueOption.ofNullable // evaluates to ValueSome 42 Convert the value option to a Nullable value. The input value option. The result value. (ValueNone: int ValueOption) |> ValueOption.toNullable // evaluates to new System.Nullable<int>() ValueSome 42 |> ValueOption.toNullable // evaluates to new System.Nullable(42) Convert the value option to a list of length 0 or 1. The input value option. The result list. (ValueNone: int ValueOption) |> ValueOption.toList // evaluates to [] ValueSome 42 |> ValueOption.toList // evaluates to [42] Convert the value option to an array of length 0 or 1. The input value option. The result array. (ValueNone: int ValueOption) |> ValueOption.toArray // evaluates to [||] ValueSome 42 |> ValueOption.toArray // evaluates to [|42|] filter f inp evaluates to match inp with ValueNone -> ValueNone | ValueSome x -> if f x then ValueSome x else ValueNone. A function that evaluates whether the value contained in the value option should remain, or be filtered out. The input value option. The input if the predicate evaluates to true; otherwise, ValueNone. ValueNone |> ValueOption.filter (fun x -> x >= 5) // evaluates to ValueNone ValueSome 42 |> ValueOption.filter (fun x -> x >= 5) // evaluates to ValueSome 42 ValueSome 4 |> ValueOption.filter (fun x -> x >= 5) // evaluates to ValueNone flatten inp evaluates to match inp with ValueNone -> ValueNone | ValueSome x -> x The input value option. The input value if the value is Some; otherwise, ValueNone. flatten is equivalent to bind id. (ValueNone: int ValueOption ValueOption) |> ValueOption.flatten // evaluates to ValueNone (ValueSome ((ValueNone: int ValueOption))) |> ValueOption.flatten // evaluates to ValueNone (ValueSome (ValueSome 42)) |> ValueOption.flatten // evaluates to ValueSome 42 bind f inp evaluates to match inp with ValueNone -> ValueNone | ValueSome x -> f x A function that takes the value of type T from a value option and transforms it into a value option containing a value of type U. The input value option. An option of the output type of the binder. let tryParse input = match System.Int32.TryParse (input: string) with | true, v -> ValueSome v | false, _ -> ValueNone ValueNone |> ValueOption.bind tryParse // evaluates to ValueNone ValueSome "42" |> ValueOption.bind tryParse // evaluates to ValueSome 42 ValueSome "Forty-two" |> ValueOption.bind tryParse // evaluates to ValueNone map f voption1 voption2 voption3 evaluates to match voption1, voption2, voption3 with ValueSome x, ValueSome y, ValueSome z -> ValueSome (f x y z) | _ -> ValueNone. A function to apply to the value option values. The first value option. The second value option. The third value option. A value option of the input values after applying the mapping function, or ValueNone if any input is ValueNone. (ValueNone, ValueNone, ValueNone) |||> ValueOption.map3 (fun x y z -> x + y + z) // evaluates to ValueNone (ValueSome 100, ValueNone, ValueNone) |||> ValueOption.map3 (fun x y z -> x + y + z) // evaluates to ValueNone (ValueNone, ValueSome 100, ValueNone) |||> ValueOption.map3 (fun x y z -> x + y + z) // evaluates to ValueNone (ValueNone, ValueNone, ValueSome 100) |||> ValueOption.map3 (fun x y z -> x + y + z) // evaluates to ValueNone (ValueSome 5, ValueSome 100, ValueSome 10) |||> ValueOption.map3 (fun x y z -> x + y + z) // evaluates to ValueSome 115 map f voption1 voption2 evaluates to match voption1, voption2 with ValueSome x, ValueSome y -> ValueSome (f x y) | _ -> ValueNone. A function to apply to the voption values. The first value option. The second value option. A value option of the input values after applying the mapping function, or ValueNone if either input is ValueNone. (ValueNone, ValueNone) ||> ValueOption.map2 (fun x y -> x + y) // evaluates to ValueNone (ValueSome 5, ValueNone) ||> ValueOption.map2 (fun x y -> x + y) // evaluates to ValueNone (ValueNone, ValueSome 10) ||> ValueOption.map2 (fun x y -> x + y) // evaluates to ValueNone (ValueSome 5, ValueSome 10) ||> ValueOption.map2 (fun x y -> x + y) // evaluates to ValueSome 15 map f inp evaluates to match inp with ValueNone -> ValueNone | ValueSome x -> ValueSome (f x). A function to apply to the voption value. The input value option. A value option of the input value after applying the mapping function, or ValueNone if the input is ValueNone. ValueNone |> ValueOption.map (fun x -> x * 2) // evaluates to ValueNone ValueSome 42 |> ValueOption.map (fun x -> x * 2) // evaluates to ValueSome 84 iter f inp executes match inp with ValueNone -> () | ValueSome x -> f x. A function to apply to the voption value. The input value option. ValueNone |> ValueOption.iter (printfn "%s") // does nothing ValueSome "Hello world" |> ValueOption.iter (printfn "%s") // prints "Hello world" Evaluates to true if is ValueSome and its value is equal to . The value to test for equality. The input value option. True if the option is ValueSome and contains a value equal to , otherwise false. (99, ValueNone) ||> ValueOption.contains // evaluates to false (99, ValueSome 99) ||> ValueOption.contains // evaluates to true (99, ValueSome 100) ||> ValueOption.contains // evaluates to false forall p inp evaluates to match inp with ValueNone -> true | ValueSome x -> p x. A function that evaluates to a boolean when given a value from the value option type. The input value option. True if the option is None, otherwise it returns the result of applying the predicate to the option value. ValueNone |> ValueOption.forall (fun x -> x >= 5) // evaluates to true ValueSome 42 |> ValueOption.forall (fun x -> x >= 5) // evaluates to true ValueSome 4 |> ValueOption.forall (fun x -> x >= 5) // evaluates to false exists p inp evaluates to match inp with ValueNone -> false | ValueSome x -> p x. A function that evaluates to a boolean when given a value from the option type. The input value option. False if the option is ValueNone, otherwise it returns the result of applying the predicate to the option value. ValueNone |> ValueOption.exists (fun x -> x >= 5) // evaluates to false ValueSome 42 |> ValueOption.exists (fun x -> x >= 5) // evaluates to true ValueSome 4 |> ValueOption.exists (fun x -> x >= 5) // evaluates to false fold f inp s evaluates to match inp with ValueNone -> s | ValueSome x -> f x s. A function to update the state data when given a value from a value option. The input value option. The initial state. The original state if the option is ValueNone, otherwise it returns the updated state with the folder and the voption value. (ValueNone, 0) ||> ValueOption.foldBack (fun x accum -> accum + x * 2) // evaluates to 0 (ValueSome 1, 0) ||> ValueOption.foldBack (fun x accum -> accum + x * 2) // evaluates to 2 (ValueSome 1, 10) ||> ValueOption.foldBack (fun x accum -> accum + x * 2) // evaluates to 12 fold f s inp evaluates to match inp with ValueNone -> s | ValueSome x -> f s x. A function to update the state data when given a value from a value option. The initial state. The input value option. The original state if the option is ValueNone, otherwise it returns the updated state with the folder and the voption value. (0, ValueNone) ||> ValueOption.fold (fun accum x -> accum + x * 2) // evaluates to 0 (0, ValueSome 1) ||> ValueOption.fold (fun accum x -> accum + x * 2) // evaluates to 2 (10, ValueSome 1) ||> ValueOption.fold (fun accum x -> accum + x * 2) // evaluates to 12 count inp evaluates to match inp with ValueNone -> 0 | ValueSome _ -> 1. The input value option. A zero if the option is ValueNone, a one otherwise. ValueNone |> ValueOption.count // evaluates to 0 ValueSome 99 |> ValueOption.count // evaluates to 1 Gets the value associated with the option. The input value option. The value within the option. Thrown when the option is ValueNone. ValueSome 42 |> ValueOption.get // evaluates to 42 (ValueNone: int ValueOption) |> ValueOption.get // throws exception! Returns if it is Some, otherwise evaluates and returns the result. A thunk that provides an alternate value option when evaluated. The input value option. The voption if the voption is ValueSome, else the result of evaluating . is not evaluated unless is ValueNone. (ValueNone: int ValueOption) |> ValueOption.orElseWith (fun () -> ValueNone) // evaluates to ValueNone ValueNone |> ValueOption.orElseWith (fun () -> (ValueSome 99)) // evaluates to ValueSome 99 ValueSome 42 |> ValueOption.orElseWith (fun () -> ValueNone) // evaluates to ValueSome 42 ValueSome 42 |> ValueOption.orElseWith (fun () -> (ValueSome 99)) // evaluates to ValueSome 42 Returns if it is Some, otherwise returns . The value to use if is None. The input option. The option if the option is Some, else the alternate option. ((ValueNone: int ValueOption), ValueNone) ||> ValueOption.orElse // evaluates to ValueNone (ValueSome 99, ValueNone) ||> ValueOption.orElse // evaluates to ValueSome 99 (ValueNone, ValueSome 42) ||> ValueOption.orElse // evaluates to ValueSome 42 (ValueSome 99, ValueSome 42) ||> ValueOption.orElse // evaluates to ValueSome 42 Gets the value of the voption if the voption is ValueSome, otherwise evaluates and returns the result. A thunk that provides a default value when evaluated. The input voption. The voption if the voption is ValueSome, else the result of evaluating . is not evaluated unless is ValueNone. ValueNone |> ValueOption.defaultWith (fun () -> 99) // evaluates to 99 ValueSome 42 |> ValueOption.defaultWith (fun () -> 99) // evaluates to 42 Gets the value of the value option if the option is ValueSome, otherwise returns the specified default value. The specified default value. The input voption. The voption if the voption is ValueSome, else the default value. Identical to the built-in operator, except with the arguments swapped. (99, ValueNone) ||> ValueOption.defaultValue // evaluates to 99 (99, ValueSome 42) ||> ValueOption.defaultValue // evaluates to 42 Returns true if the value option is ValueNone. The input value option. True if the voption is ValueNone. ValueNone |> ValueOption.isNone // evaluates to true ValueSome 42 |> ValueOption.isNone // evaluates to false Returns true if the value option is not ValueNone. The input value option. True if the value option is not ValueNone. ValueNone |> ValueOption.isSome // evaluates to false ValueSome 42 |> ValueOption.isSome // evaluates to true Contains operations for working with value options. Options Convert an option to a value option. The input option. The resulting value option. Some 42 |> Option.toValueOption // evaluates to ValueSome 42 (None: int option) |> Option.toValueOption // evaluates to ValueNone Convert a value option to an option. The input value option. The resulting option. ValueSome 42 |> Option.ofValueOption // evaluates to Some 42 (ValueNone: int voption) |> Option.ofValueOption // evaluates to None Convert an option to a potentially null value. The input value. The result value, which is null if the input was None. (None: string option) |> Option.toObj // evaluates to null Some "not a null string" |> Option.toObj // evaluates to "not a null string" Convert a potentially null value to an option. The input value. The result option. (null: string) |> Option.ofObj // evaluates to None "not a null string" |> Option.ofObj // evaluates to (Some "not a null string") Convert a Nullable value to an option. The input nullable value. The result option. System.Nullable<int>() |> Option.ofNullable // evaluates to None System.Nullable(42) |> Option.ofNullable // evaluates to Some 42 Convert the option to a Nullable value. The input option. The result value. (None: int option) |> Option.toNullable // evaluates to new System.Nullable<int>() Some 42 |> Option.toNullable // evaluates to new System.Nullable(42) Convert the option to a list of length 0 or 1. The input option. The result list. (None: int option) |> Option.toList // evaluates to [] Some 42 |> Option.toList // evaluates to [42] Convert the option to an array of length 0 or 1. The input option. The result array. (None: int option) |> Option.toArray // evaluates to [||] Some 42 |> Option.toArray // evaluates to [|42|] filter f inp evaluates to match inp with None -> None | Some x -> if f x then Some x else None. A function that evaluates whether the value contained in the option should remain, or be filtered out. The input option. The input if the predicate evaluates to true; otherwise, None. None |> Option.filter (fun x -> x >= 5) // evaluates to None Some 42 |> Option.filter (fun x -> x >= 5) // evaluates to Some 42 Some 4 |> Option.filter (fun x -> x >= 5) // evaluates to None flatten inp evaluates to match inp with None -> None | Some x -> x The input option. The input value if the value is Some; otherwise, None. flatten is equivalent to bind id. (None: int option option) |> Option.flatten // evaluates to None (Some ((None: int option))) |> Option.flatten // evaluates to None (Some (Some 42)) |> Option.flatten // evaluates to Some 42 bind f inp evaluates to match inp with None -> None | Some x -> f x A function that takes the value of type T from an option and transforms it into an option containing a value of type U. The input option. An option of the output type of the binder. let tryParse (input: string) = match System.Int32.TryParse input with | true, v -> Some v | false, _ -> None None |> Option.bind tryParse // evaluates to None Some "42" |> Option.bind tryParse // evaluates to Some 42 Some "Forty-two" |> Option.bind tryParse // evaluates to None map f option1 option2 option3 evaluates to match option1, option2, option3 with Some x, Some y, Some z -> Some (f x y z) | _ -> None. A function to apply to the option values. The first option. The second option. The third option. An option of the input values after applying the mapping function, or None if any input is None. (None, None, None) |||> Option.map3 (fun x y z -> x + y + z) // evaluates to None (Some 100, None, None) |||> Option.map3 (fun x y z -> x + y + z) // evaluates to None (None, Some 100, None) |||> Option.map3 (fun x y z -> x + y + z) // evaluates to None (None, None, Some 100) |||> Option.map3 (fun x y z -> x + y + z) // evaluates to None (Some 5, Some 100, Some 10) |||> Option.map3 (fun x y z -> x + y + z) // evaluates to Some 115 map f option1 option2 evaluates to match option1, option2 with Some x, Some y -> Some (f x y) | _ -> None. A function to apply to the option values. The first option. The second option. An option of the input values after applying the mapping function, or None if either input is None. (None, None) ||> Option.map2 (fun x y -> x + y) // evaluates to None (Some 5, None) ||> Option.map2 (fun x y -> x + y) // evaluates to None (None, Some 10) ||> Option.map2 (fun x y -> x + y) // evaluates to None (Some 5, Some 10) ||> Option.map2 (fun x y -> x + y) // evaluates to Some 15 map f inp evaluates to match inp with None -> None | Some x -> Some (f x). A function to apply to the option value. The input option. An option of the input value after applying the mapping function, or None if the input is None. None |> Option.map (fun x -> x * 2) // evaluates to None Some 42 |> Option.map (fun x -> x * 2) // evaluates to Some 84 iter f inp executes match inp with None -> () | Some x -> f x. A function to apply to the option value. The input option. None |> Option.iter (printfn "%s") // does nothing Some "Hello world" |> Option.iter (printfn "%s") // prints "Hello world" Evaluates to true if is Some and its value is equal to . The value to test for equality. The input option. True if the option is Some and contains a value equal to , otherwise false. (99, None) ||> Option.contains // evaluates to false (99, Some 99) ||> Option.contains // evaluates to true (99, Some 100) ||> Option.contains // evaluates to false forall p inp evaluates to match inp with None -> true | Some x -> p x. A function that evaluates to a boolean when given a value from the option type. The input option. True if the option is None, otherwise it returns the result of applying the predicate to the option value. None |> Option.forall (fun x -> x >= 5) // evaluates to true Some 42 |> Option.forall (fun x -> x >= 5) // evaluates to true Some 4 |> Option.forall (fun x -> x >= 5) // evaluates to false exists p inp evaluates to match inp with None -> false | Some x -> p x. A function that evaluates to a boolean when given a value from the option type. The input option. False if the option is None, otherwise it returns the result of applying the predicate to the option value. None |> Option.exists (fun x -> x >= 5) // evaluates to false Some 42 |> Option.exists (fun x -> x >= 5) // evaluates to true Some 4 |> Option.exists (fun x -> x >= 5) // evaluates to false fold f inp s evaluates to match inp with None -> s | Some x -> f x s. A function to update the state data when given a value from an option. The input option. The initial state. The original state if the option is None, otherwise it returns the updated state with the folder and the option value. (None, 0) ||> Option.foldBack (fun x accum -> accum + x * 2) // evaluates to 0 (Some 1, 0) ||> Option.foldBack (fun x accum -> accum + x * 2) // evaluates to 2 (Some 1, 10) ||> Option.foldBack (fun x accum -> accum + x * 2) // evaluates to 12 fold f s inp evaluates to match inp with None -> s | Some x -> f s x. A function to update the state data when given a value from an option. The initial state. The input option. The original state if the option is None, otherwise it returns the updated state with the folder and the option value. (0, None) ||> Option.fold (fun accum x -> accum + x * 2) // evaluates to 0 (0, Some 1) ||> Option.fold (fun accum x -> accum + x * 2) // evaluates to 2 (10, Some 1) ||> Option.fold (fun accum x -> accum + x * 2) // evaluates to 12 count inp evaluates to match inp with None -> 0 | Some _ -> 1. The input option. A zero if the option is None, a one otherwise. None |> Option.count // evaluates to 0 Some 99 |> Option.count // evaluates to 1 Gets the value associated with the option. The input option. The value within the option. Thrown when the option is None. Some 42 |> Option.get // evaluates to 42 (None: int option) |> Option.get // throws exception! Returns if it is Some, otherwise evaluates and returns the result. A thunk that provides an alternate option when evaluated. The input option. The option if the option is Some, else the result of evaluating . is not evaluated unless is None. (None: int Option) |> Option.orElseWith (fun () -> None) // evaluates to None None |> Option.orElseWith (fun () -> (Some 99)) // evaluates to Some 99 Some 42 |> Option.orElseWith (fun () -> None) // evaluates to Some 42 Some 42 |> Option.orElseWith (fun () -> (Some 99)) // evaluates to Some 42 Returns if it is Some, otherwise returns . The value to use if is None. The input option. The option if the option is Some, else the alternate option. ((None: int Option), None) ||> Option.orElse // evaluates to None (Some 99, None) ||> Option.orElse // evaluates to Some 99 (None, Some 42) ||> Option.orElse // evaluates to Some 42 (Some 99, Some 42) ||> Option.orElse // evaluates to Some 42 Gets the value of the option if the option is Some, otherwise evaluates and returns the result. A thunk that provides a default value when evaluated. The input option. The option if the option is Some, else the result of evaluating . is not evaluated unless is None. None |> Option.defaultWith (fun () -> 99) // evaluates to 99 Some 42 |> Option.defaultWith (fun () -> 99) // evaluates to 42 Gets the value of the option if the option is Some, otherwise returns the specified default value. The specified default value. The input option. The option if the option is Some, else the default value. Identical to the built-in operator, except with the arguments swapped. (99, None) ||> Option.defaultValue // evaluates to 99 (99, Some 42) ||> Option.defaultValue // evaluates to 42 Returns true if the option is None. The input option. True if the option is None. None |> Option.isNone // evaluates to true Some 42 |> Option.isNone // evaluates to false Returns true if the option is not None. The input option. True if the option is not None. None |> Option.isSome // evaluates to false Some 42 |> Option.isSome // evaluates to true Contains operations for working with options. Options Convert the result to an Option value. The input result. The result value. Error 42 |> Result.toOption // evaluates to ValueNone Ok 42 |> Result.toOption // evaluates to ValueSome 42 Convert the result to an Option value. The input result. The option value. Error 42 |> Result.toOption // evaluates to None Ok 42 |> Result.toOption // evaluates to Some 42 Convert the result to a list of length 0 or 1. The input result. The result list. Error 42 |> Result.toList // evaluates to [] Ok 42 |> Result.toList // evaluates to [ 42 ] Convert the result to an array of length 0 or 1. The input result. The result array. Error 42 |> Result.toArray // evaluates to [||] Ok 42 |> Result.toArray // evaluates to [| 42 |] iter f inp executes match inp with Error _ -> () | Ok x -> f x. A function to apply to the result value. The input result. Error "Hello world" |> Result.iter (printfn "%s") // does nothing Ok "Hello world" |> Result.iter (printfn "%s") // prints "Hello world" Evaluates to true if is Ok and its value is equal to . The value to test for equality. The input result. True if the result is Ok and contains a value equal to , otherwise false. (99, Error 99) ||> Result.contains // evaluates to false (99, Ok 99) ||> Result.contains // evaluates to true (99, Ok 100) ||> Result.contains // evaluates to false forall p inp evaluates to match inp with Error _ -> true | Ok x -> p x. A function that evaluates to a boolean when given a value from the result type. The input result. True if the result is Error, otherwise it returns the result of applying the predicate to the result value. Error 1 |> Result.forall (fun x -> x >= 5) // evaluates to true Ok 42 |> Result.forall (fun x -> x >= 5) // evaluates to true Ok 4 |> Result.forall (fun x -> x >= 5) // evaluates to false exists p inp evaluates to match inp with Error _ -> false | Ok x -> p x. A function that evaluates to a boolean when given a value from the result type. The input result. False if the result is Error, otherwise it returns the result of applying the predicate to the result value. Error 6 |> Result.exists (fun x -> x >= 5) // evaluates to false Ok 42 |> Result.exists (fun x -> x >= 5) // evaluates to true Ok 4 |> Result.exists (fun x -> x >= 5) // evaluates to false foldBack f inp s evaluates to match inp with Error _ -> s | Ok x -> f x s. A function to update the state data when given a value from an result. The input result. The initial state. The original state if the result is Error, otherwise it returns the updated state with the folder and the result value. (Error 2, 0) ||> Result.foldBack (fun x accum -> accum + x * 2) // evaluates to 0 (Ok 1, 0) ||> Result.foldBack (fun x accum -> accum + x * 2) // evaluates to 2 (Ok 1, 10) ||> Result.foldBack (fun x accum -> accum + x * 2) // evaluates to 12 fold f s inp evaluates to match inp with Error _ -> s | Ok x -> f s x. A function to update the state data when given a value from an result. The initial state. The input result. The original state if the result is Error, otherwise it returns the updated state with the folder and the result value. (0, Error 2) ||> Result.fold (fun accum x -> accum + x * 2) // evaluates to 0 (0, Ok 1) ||> Result.fold (fun accum x -> accum + x * 2) // evaluates to 2 (10, Ok 1) ||> Result.fold (fun accum x -> accum + x * 2) // evaluates to 12 count inp evaluates to match inp with Error _ -> 0 | Ok _ -> 1. The input result. A zero if the result is Error, a one otherwise. Error 99 |> Result.count // evaluates to 0 Ok 99 |> Result.count // evaluates to 1 Gets the value of the result if the result is Ok, otherwise evaluates and returns the result. A thunk that provides a default value when evaluated. The input result. The result if the result is Ok, else the result of evaluating . is not evaluated unless is Error. Ok 1 |> Result.defaultWith (fun error -> 99) // evaluates to 1 Error 2 |> Result.defaultWith (fun error -> 99) // evaluates to 99 Gets the value of the result if the result is Ok, otherwise returns the specified default value. The specified default value. The input result. The result if the result is Ok, else the default value. Result.defaultValue 2 (Error 3) // evaluates to 2 Result.defaultValue 2 (Ok 1) // evaluates to 1 Returns true if the result is Error. The input result. True if the result is Error. Ok 42 |> Result.isError // evaluates to false Error 42 |> Result.isError // evaluates to true Returns true if the result is Ok. The input result. True if the result is OK. Ok 42 |> Result.isOk // evaluates to true Error 42 |> Result.isOk // evaluates to false bind f inp evaluates to match inp with Error e -> Error e | Ok x -> f x A function that takes the value of type T from a result and transforms it into a result containing a value of type U. The input result. A result of the output type of the binder. let tryParse (input: string) = match System.Int32.TryParse input with | true, v -> Ok v | false, _ -> Error "couldn't parse" Error "message" |> Result.bind tryParse // evaluates to Error "message" Ok "42" |> Result.bind tryParse // evaluates to Ok 42 Ok "Forty-two" |> Result.bind tryParse // evaluates to Error "couldn't parse" map f inp evaluates to match inp with Error x -> Error (f x) | Ok v -> Ok v. A function to apply to the Error result value. The input result. A result of the error value after applying the mapping function, or Ok if the input is Ok. Ok 1 |> Result.mapError (fun x -> "bar") // evaluates to Ok 1 Error "foo" |> Result.mapError (fun x -> "bar") // evaluates to Error "bar" map f inp evaluates to match inp with Error e -> Error e | Ok x -> Ok (f x). A function to apply to the OK result value. The input result. A result of the input value after applying the mapping function, or Error if the input is Error. Ok 1 |> Result.map (fun x -> "perfect") // evaluates to Ok "perfect" Error "message" |> Result.map (fun x -> "perfect") // evaluates to Error "message" Contains operations for working with values of type . Choices and Results Returns a string by concatenating count instances of str. The number of copies of the input string will be copied. The input string. The concatenated string. Thrown when count is negative. "Do it!" |> String.replicate 3 Evaluates to "Do it!Do it!Do it!". Builds a new string whose characters are the results of applying the function mapping to each character and index of the input string. The function to apply to each character and index of the string. The input string. The resulting string. input |> String.mapi (fun i c -> (i, c)) Evaluates to [ (0, 'O'); (1, 'K'); (2, '!') ]. Builds a new string whose characters are the results of applying the function mapping to each of the characters of the input string. The function to apply to the characters of the string. The input string. The resulting string. Changing case to upper for all characters in the input string open System let input = "Hello there!" input |> String.map Char.ToUpper // evaluates "HELLO THERE!" Returns the length of the string. The input string. The number of characters in the string. Getting the length of different strings String.length null // evaluates 0 String.length "" // evaluates 0 String.length "123" // evaluates 3 Applies the function action to the index of each character in the string and the character itself. The function to apply to each character and index of the string. The input string. Numbering the characters and printing the associated ASCII code for each character in the input string let input = "Hello" input |> String.iteri (fun i c -> printfn "%d. %c %d" (i + 1) c (int c)) The sample evaluates as unit, but prints: 1. H 72 2. e 101 3. l 108 4. l 108 5. o 111 Applies the function action to each character in the string. The function to be applied to each character of the string. The input string. Printing the ASCII code for each character in the string let input = "Hello" input |> String.iter (fun c -> printfn "%c %d" c (int c)) The sample evaluates as unit, but prints: H 72 e 101 l 108 l 108 o 111 Builds a new string whose characters are the results of applying the function mapping to each index from 0 to count-1 and concatenating the resulting strings. The number of strings to initialize. The function to take an index and produce a string to be concatenated with the others. The constructed string. Thrown when count is negative. Enumerate digits ASCII codes String.init 10 (fun i -> int '0' + i |> sprintf "%d ") The sample evaluates to: "48 49 50 51 52 53 54 55 56 57 " Tests if all characters in the string satisfy the given predicate. The function to test each character of the string. The input string. True if all characters return true for the predicate and false otherwise. Looking for lowercase characters open System "all are lower" |> String.forall Char.IsLower // evaluates false "allarelower" |> String.forall Char.IsLower // evaluates true Builds a new string containing only the characters of the input string for which the given predicate returns "true". Returns an empty string if the input string is null A function to test whether each character in the input sequence should be included in the output string. The input string. The resulting string. Filtering out just alphanumeric characters open System let input = "0 1 2 3 4 5 6 7 8 9 a A m M" input |> String.filter Uri.IsHexDigit // evaluates "123456789aA" Filtering out just digits open System "hello" |> String.filter Char.IsDigit // evaluates "" Tests if any character of the string satisfies the given predicate. The function to test each character of the string. The input string. True if any character returns true for the predicate and false otherwise. Looking for uppercase characters open System "Yoda" |> String.exists Char.IsUpper // evaluates true "nope" |> String.exists Char.IsUpper // evaluates false Returns a new string made by concatenating the given strings with separator sep, that is a1 + sep + ... + sep + aN. The separator string to be inserted between the strings of the input sequence. The sequence of strings to be concatenated. A new string consisting of the concatenated strings separated by the separation string. Thrown when strings is null. let input1 = ["Stefan"; "says:"; "Hello"; "there!"] input1 |> String.concat " " // evaluates "Stefan says: Hello there!" let input2 = [0..9] |> List.map string input2 |> String.concat "" // evaluates "0123456789" input2 |> String.concat ", " // evaluates "0, 1, 2, 3, 4, 5, 6, 7, 8, 9" let input3 = ["No comma"] input3 |> String.concat "," // evaluates "No comma" Builds a new string whose characters are the results of applying the function mapping to each of the characters of the input string and concatenating the resulting strings. The function to produce a string from each character of the input string. The input string. The concatenated string. The following samples shows how to interspace spaces in a text let input = "Stefan says: Hi!" input |> String.collect (sprintf "%c ") The sample evaluates to "S t e f a n s a y s : H i ! " How to show the ASCII representation of a very secret text "Secret" |> String.collect (fun chr -> int chr |> sprintf "%d ") The sample evaluates to "83 101 99 114 101 116 " Functional programming operators for string processing. Further string operations are available via the member functions on strings and other functionality in System.String and System.Text.RegularExpressions types. Strings and Text Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Provides a default implementations of F# numeric literal syntax for literals of the form 'dddI' Language Primitives Represents a statically-analyzed format associated with writing to a . The type parameter indicates the arguments and return type of the format operation. Represents a statically-analyzed format when formatting builds a string. The type parameter indicates the arguments and return type of the format operation. Represents a statically-analyzed format associated with writing to a . The type parameter indicates the arguments and return type of the format operation. Represents a statically-analyzed format associated with writing to a . The first type parameter indicates the arguments of the format operation and the last the overall return type. Represents a statically-analyzed format when formatting builds a string. The first type parameter indicates the arguments of the format operation and the last the overall return type. Represents a statically-analyzed format associated with writing to a . The first type parameter indicates the arguments of the format operation and the last the overall return type. Print to a string buffer and raise an exception with the given result. Helper printers must return strings. The input formatter. The arguments of the formatter. failwithf "That's wrong. Five = %d and six = %d" (3+2) (3+3) Throws Exception with message "That's wrong. Five = 5 and six = 6". sprintf, but call the given 'final' function to generate the result. See kprintf. The function called to generate a result from the formatted string. The input formatter. The arguments of the formatter. Using % format patterns: open Printf ksprintf (fun s -> s + ", done!") $"Write three = {1+2}" Evaluates to "Write three = 3, done!". printf, but call the given 'final' function to generate the result. For example, these let the printing force a flush after all output has been entered onto the channel, but not before. The function called after formatting to generate the format result. The input formatter. The arguments of the formatter. Using % format patterns: open Printf kprintf (fun s -> s + ", done!") $"Write three = {1+2}" Evaluates to "Write three = 3, done!". fprintf, but call the given 'final' function to generate the result. See kprintf. The function called after formatting to generate the format result. The input TextWriter. The input formatter. The arguments of the formatter. Using % format patterns: open Printf open System.IO let file = File.CreateText("out.txt") kfprintf (fun () -> file.Close()) file $"Write three = {1+2}" Writes "Write three = 3" to out.txt. bprintf, but call the given 'final' function to generate the result. See kprintf. The function called after formatting to generate the format result. The input StringBuilder. The input formatter. The arguments of the formatter. Using % format patterns: open Printf open System.Text let buffer = new StringBuilder() kbprintf (fun () -> buffer.ToString()) buffer "Write five = %d" (3+2) Evaluates to "Write five = 5". Print to a string via an internal string buffer and return the result as a string. Helper printers must return strings. The input formatter. The formatted string. sprintf "Write five = %d and six = %d" (3+2) (3+3) Evaluates to "Write five = 5 and six = 6". Formatted printing to stdout, adding a newline. The input formatter. The return type and arguments of the formatter. Using interpolated strings: printfn $"Write three = {1+2}" printfn $"Write four = {2+2}" After evaluation the two lines are written to stdout. Using % format patterns: printfn "Write five = %d" (3+2) printfn "Write six = %d" (3+3) After evaluation the two lines are written to stdout. Formatted printing to stdout The input formatter. The return type and arguments of the formatter. Using interpolated strings: printf $"Write three = {1+2}" After evaluation the text "Write three = 3" is written to stdout. Using % format patterns: printf "Write five = %d" (3+2) After evaluation the text "Write five = 5" is written to stdout. Formatted printing to stderr, adding a newline The input formatter. The return type and arguments of the formatter. Using interpolated strings: eprintfn $"Write three = {1+2}" eprintfn $"Write four = {2+2}" After evaluation two lines are written to stderr. Using % format patterns: eprintfn "Write five = %d" (3+2) eprintfn "Write six = %d" (3+3) After evaluation two lines are written to stderr. Formatted printing to stderr The input formatter. The return type and arguments of the formatter. Using interpolated strings: eprintf $"Write three = {1+2}" After evaluation the text "Write three = 3" is written to stderr. Using % format patterns: eprintf "Write five = %d" (3+2) After evaluation the text "Write five = 5" is written to stderr. Print to a text writer, adding a newline The TextWriter to print to. The input formatter. The return type and arguments of the formatter. Using interpolated strings: open Printf open System.IO let file = File.CreateText("out.txt") fprintfn file $"Write three = {1+2}" fprintfn file $"Write four = {2+2}" file.Close() After evaluation the file contains two lines. Using % format patterns: open Printf open System.IO let file = File.CreateText("out.txt") fprintfn file "Write five = %d" (3+2) fprintfn file "Write six = %d" (3+3) file.Close() After evaluation the file contains two lines. Print to a text writer. The TextWriter to print to. The input formatter. The return type and arguments of the formatter. Using interpolated strings: open Printf open System.IO let file = File.CreateText("out.txt") fprintf file $"Write three = {1+2}" file.Close() After evaluation the file contains the text "Write three = 3". Using % format patterns: open Printf open System.IO let file = File.CreateText("out.txt") fprintf file "Write five = %d" (3+2) file.Close() After evaluation the file contains the text "Write five = 5". Print to a The StringBuilder to print to. The input format or interpolated string. The return type and arguments of the formatter. Using interpolated strings: open Printf open System.Text let buffer = new StringBuilder() bprintf buffer $"Write three = {1+2}" buffer.ToString() Evaluates to "Write three = 3". Using % format patterns: open Printf open System.Text let buffer = new StringBuilder() bprintf buffer "Write five = %d" (3+2) buffer.ToString() Evaluates to "Write five = 5". Extensible printf-style formatting for numbers and other datatypes Format specifications are strings with "%" markers indicating format placeholders. Format placeholders consist of %[flags][width][.precision][type]. Strings and Text Return the resulting list Add multiple elements to the collector and return the resulting array Add multiple elements to the collector Add an element to the collector Collects elements and builds an array Return the resulting list Add multiple elements to the collector and return the resulting list Add multiple elements to the collector Add an element to the collector Collects elements and builds a list The F# compiler emits implementations of this type for compiled sequence expressions. The F# compiler emits implementations of this type for compiled sequence expressions. The F# compiler emits implementations of this type for compiled sequence expressions. A new enumerator for the sequence. The F# compiler emits implementations of this type for compiled sequence expressions. A reference to the sequence. A 0, 1, and 2 respectively indicate Stop, Yield, and Goto conditions for the sequence generator. The F# compiler emits implementations of this type for compiled sequence expressions. The F# compiler emits implementations of this type for compiled sequence expressions. A new sequence generator for the expression. The F# compiler emits implementations of this type for compiled sequence expressions. Creates an instance of the attribute NoEagerConstraintApplicationAttribute Adding this attribute to the method adjusts the processing of some generic methods during overload resolution. During overload resolution, caller arguments are matched with called arguments to extract type information. By default, when the caller argument type is unconstrained (for example a simple value x without known type information), and a method qualifies for lambda constraint propagation, then member trait constraints from a method overload are eagerly applied to the caller argument type. This causes that overload to be preferred, regardless of other method overload resolution rules. Using this attribute suppresses this behaviour. Consider the following overloads: type OverloadsWithSrtp() = [<NoEagerConstraintApplicationAttribute>] static member inline SomeMethod< ^T when ^T : (member Number: int) > (x: ^T, f: ^T -> int) = 1 static member SomeMethod(x: 'T list, f: 'T list -> int) = 2 let inline f x = OverloadsWithSrtp.SomeMethod (x, (fun a -> 1)) With the attribute, the overload resolution fails, because both members are applicable. Without the attribute, the overload resolution succeeds, because the member constraint is eagerly applied, making the second member non-applicable. Attributes Defines the implementation of the code run after the creation of a struct state machine. Defines the implementation of the SetStateMachine method for a struct state machine. Defines the implementation of the MoveNext method for a struct state machine. A special compiler-recognised delegate type for specifying blocks of resumable code with access to the state machine. Represents the runtime continuation of a resumable state machine created dynamically The continuation of the state machine Additional data associated with the state machine The continuation of the state machine Additional data associated with the state machine Executes the SetStateMachine implementation of the state machine Executes the MoveNext implementation of the state machine Create dynamic information for a state machine Represents the delegated runtime continuation of a resumable state machine created dynamically Copy-out or copy-in the data of the state machine Get the resumption point of the state machine Copy-out or copy-in the data of the state machine Represents the delegated runtime continuation for a resumable state machine created dynamically This field is removed from state machines generated using '__stateMachine'. Resumable code used in state machines which accesses this field will raise a runtime exception. When statically compiled, holds the continuation goto-label further execution of the state machine When statically compiled, holds the data for the state machine Acts as a template for struct state machines introduced by __stateMachine, and also as a reflective implementation Get the static parameters for a provided method. A method returned by GetMethod on a provided type The static parameters of the provided method, if any Apply static arguments to a provided method that accepts static arguments. The provider must return a provided method with the given mangled name. the provided method definition which has static parameters the full name of the method that must be returned, including encoded representations of static parameters the values of the static parameters, indexed by name The provided method definition corresponding to the given static parameter values Represents additional, optional information for a type provider component Triggered when an assumption changes that invalidates the resolutions so far reported by the provider Triggered when an assumption changes that invalidates the resolutions so far reported by the provider Triggered when an assumption changes that invalidates the resolutions so far reported by the provider Get the static parameters for a provided type. A type returned by GetTypes or ResolveTypeName Gets the namespaces provided by the type provider. Called by the compiler to ask for an Expression tree to replace the given MethodBase with. MethodBase that was given to the compiler by a type returned by a GetType(s) call. Expressions that represent the parameters to this call. An expression that the compiler will use in place of the given method base. Get the physical contents of the given logical provided assembly. Apply static arguments to a provided type that accepts static arguments. The provider must return a type with the given mangled name. the provided type definition which has static parameters the full path of the type, including encoded representations of static parameters the static parameters, indexed by name Represents an instantiation of a type provider component. Namespace name the provider injects types into. Compilers call this method to query a type provider for a type name. Resolver should return a type called name in namespace NamespaceName or null if the type is unknown. The top-level types The sub-namespaces in this namespace. An optional member to prevent generation of namespaces until an outer namespace is explored. Represents a namespace provided by a type provider component. Get the full path to use for temporary files for the type provider instance. version of referenced system runtime assembly Get the full path to referenced assembly that caused this type provider instance to be created. Get the full path to use to resolve relative paths in any file name arguments given to the type provider instance. Get the referenced assemblies for the type provider instance. Indicates if the type provider host responds to invalidation events for type provider instances. Indicates if the type provider instance is used in an environment which executes provided code such as F# Interactive. Get the full path to use for temporary files for the type provider instance. version of referenced system runtime assembly Get the full path to referenced assembly that caused this type provider instance to be created. Get the full path to use to resolve relative paths in any file name arguments given to the type provider instance. Get the referenced assemblies for the type provider instance. Indicates if the type provider host responds to invalidation events for type provider instances. Indicates if the type provider instance is used in an environment which executes provided code such as F# Interactive. Checks if given type exists in target system runtime library Create a configuration which calls the given functions for the corresponding operation. Create a configuration which calls the given function for the corresponding operation. If the class that implements ITypeProvider has a constructor that accepts TypeProviderConfig then it will be constructed with an instance of TypeProviderConfig. Creates an instance of the attribute TypeProviderEditorHideMethodsAttribute Indicates that a code editor should hide all System.Object methods from the intellisense menus for instances of a provided type Gets or sets the line for the location. Gets or sets the file path for the definition location. Gets or sets the column for the location. Gets or sets the line for the location. Gets or sets the file path for the definition location. Gets or sets the column for the location. A type provider may provide an instance of this attribute to indicate the definition location for a provided type or member. Gets the comment text. Creates an instance of the attribute TypeProviderXmlDocAttribute A type provider may provide an instance of this attribute to indicate the documentation to show for a provided type or member. Gets the assembly name. Creates an instance of the attribute TypeProviderAssemblyAttribute The name of the design-time assembly for this type provider. Creates an instance of the attribute TypeProviderAssemblyAttribute Place this attribute on a runtime assembly to indicate that there is a corresponding design-time assembly that contains a type provider. Runtime and design-time assembly may be the same. Additional type attribute flags related to provided types Creates an instance of the attribute TypeProviderAttribute Place on a class that implements ITypeProvider to extend the compiler Represents the '1' measure expression when returned as a generic argument of a provided type. Represents the inverse of a measure expressions when returned as a generic argument of a provided type. Represents the product of two measure expressions when returned as a generic argument of a provided type. Library functionality for supporting type providers and code generated by the F# compiler. See also F# Type Providers in the F# Language Guide. Creates an anonymous event with the given handlers. A function to handle adding a delegate for the event to trigger. A function to handle removing a delegate that the event triggers. A function to produce the delegate type the event can trigger. The initialized event. The F# compiler emits calls to this function to implement the use operator for F# sequence expressions. The resource to be used and disposed. The input sequence. The result sequence. The F# compiler emits calls to this function to implement the compiler-intrinsic conversions from untyped IEnumerable sequences to typed sequences. An initializer function. A function to iterate and test if end of sequence is reached. A function to retrieve the current element. The resulting typed sequence. The F# compiler emits calls to this function to implement the try/with operator for F# sequence expressions. The input sequence. Pattern matches after 'when' converted to return 1 Pattern matches after 'when' with their actual execution code The result sequence. The F# compiler emits calls to this function to implement the try/finally operator for F# sequence expressions. The input sequence. A computation to be included in an enumerator's Dispose method. The result sequence. The F# compiler emits calls to this function to implement the while operator for F# sequence expressions. A function that indicates whether iteration should continue. The input sequence. The result sequence. A group of functions used as part of the compiled representation of F# sequence expressions. Statically generates a closure struct type based on ResumableStateMachine, At runtime an instance of the new struct type is populated and 'afterMethod' is called to consume it. At compile-time, the ResumableStateMachine type guides the generation of a new struct type by the F# compiler with closure-capture fields in a way similar to an object expression. Any mention of the ResumableStateMachine type in any the 'methods' is rewritten to this fresh struct type. The 'methods' are used to implement the interfaces on ResumableStateMachine and are also rewritten. The 'after' method is then executed and must eliminate the ResumableStateMachine. For example, its return type must not include ResumableStateMachine. Gives the implementation of the MoveNext method on IAsyncStateMachine. Gives the implementation of the SetStateMachine method on IAsyncStateMachine. Gives code to execute after the generation of the state machine and to produce the final result. Indicates to jump to a resumption point within resumable code. This may be the first statement in a MoveNextMethodImpl. The integer must be a valid resumption point within this resumable code. Indicates a resumption point within resumable code When used in a conditional, statically determines whether the 'then' branch represents valid resumable code and provides an alternative implementation if not. Indicates a named debug point arising from the context of inlined code. Only a limited range of debug point names are supported. If the debug point name is the empty string then the range used for the debug point will be the range of the outermost expression prior to inlining. If the debug point name is ForLoop.InOrToKeyword and the code was ultimately from a for .. in .. do or for .. = .. to .. do construct in a computation expression, de-sugared to an inlined builder.For call, then the name "ForLoop.InOrToKeyword" can be used. The range of the debug point will be precisely the range of the in or to keyword. If the name doesn't correspond to a known debug point arising from the original source context, then an opt-in warning 3514 is emitted, and the range used for the debug point will be the range of the root expression prior to inlining. Contains compiler intrinsics related to the definition of state machines. The dynamic implementation of the corresponding operation. This operation should not be used directly. The dynamic implementation of the corresponding operation. This operation should not be used directly. The dynamic implementation of the corresponding operation. This operation should not be used directly. The dynamic implementation of the corresponding operation. This operation should not be used directly. The dynamic implementation of the corresponding operation. This operation should not be used directly. Specifies resumable code which does nothing Specifies resumable code which executes a loop Specifies resumable code which executes with 'use' semantics Specifies resumable code which executes with try/with semantics Specifies resumable code which executes with try/finally semantics Specifies resumable code which executes with try/finally semantics Specifies resumable code which iterates yields Specifies resumable code which iterates an input sequence Creates resumable code whose definition is a delayed function Sequences one section of resumable code after another Contains functions for composing resumable code blocks Builds a query using query syntax and operators. let findEvensAndSortAndDouble(xs: System.Linq.IQueryable<int>) = query { for x in xs do where (x % 2 = 0) sortBy x select (x+x) } let data = [1; 2; 6; 7; 3; 6; 2; 1] findEvensAndSortAndDouble (data.AsQueryable()) |> Seq.toList Evaluates to [4; 4; 12; 12]. An active pattern to force the execution of values of type Lazy<_>. let f (Lazy v) = v + v let v = lazy (printf "eval!"; 5+5) f v f v Evaluates to 10. The text eval! is printed once on the first invocation of f. Special prefix operator for splicing untyped expressions into quotation holes. let f v = <@@ (%%v: int) + (%%v: int) @@> f <@@ 5 + 5 @@>;; Evaluates to an untyped quotation equivalent to <@@ (5 + 5) + (5 + 5) @@> Special prefix operator for splicing typed expressions into quotation holes. let f v = <@ %v + %v @> f <@ 5 + 5 @>;; Evaluates to a quotation equivalent to <@ (5 + 5) + (5 + 5) @> Builds a 2D array from a sequence of sequences of elements. array2D [ [ 1.0; 2.0 ]; [ 3.0; 4.0 ] ] Evaluates to a 2x2 zero-based array with contents [[1.0; 2.0]; [3.0; 4.0]] Builds a read-only lookup table from a sequence of key/value pairs. The key objects are indexed using generic hashing and equality. let table = readOnlyDict [ (1, 100); (2, 200) ] table[1] Evaluates to 100. let table = readOnlyDict [ (1, 100); (2, 200) ] table[3] Throws System.Collections.Generic.KeyNotFoundException. Builds a read-only lookup table from a sequence of key/value pairs. The key objects are indexed using generic hashing and equality. let table = dict [ (1, 100); (2, 200) ] table[1] Evaluates to 100. let table = dict [ (1, 100); (2, 200) ] table[3] Throws System.Collections.Generic.KeyNotFoundException. Converts the argument to signed byte. This is a direct conversion for all primitive numeric types. For strings, the input is converted using SByte.Parse() with InvariantCulture settings. Otherwise the operation requires and invokes a ToSByte method on the input type. int8 -12 Evaluates to -12y. int8 "3" Evaluates to 3y. Converts the argument to byte. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Byte.Parse() on strings and otherwise requires a ToByte method on the input type. uint8 12 Evaluates to 12uy. Converts the argument to 64-bit float. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Double.Parse() with InvariantCulture settings. Otherwise the operation requires and invokes a ToDouble method on the input type. double 45 Evaluates to 45.0. double 12.3f Evaluates to 12.30000019. Converts the argument to 32-bit float. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Single.Parse() with InvariantCulture settings. Otherwise the operation requires and invokes a ToSingle method on the input type. single 45 Evaluates to 45.0f. Builds an asynchronous workflow using computation expression syntax. let sleepExample() = async { printfn "sleeping" do! Async.Sleep 10 printfn "waking up" return 6 } sleepExample() |> Async.RunSynchronously Builds a set from a sequence of objects. The objects are indexed using generic comparison. The input sequence of elements. The created set. let values = set [ 1; 2; 3; 5; 7; 11 ] Evaluates to a set containing the given numbers. Print to a file using the given format, and add a newline. The file TextWriter. The formatter. The formatted result. See Printf.fprintfn (link: ) for examples. Print to a file using the given format. The file TextWriter. The formatter. The formatted result. See Printf.fprintf (link: ) for examples. Print to a string buffer and raise an exception with the given result. Helper printers must return strings. The formatter. The formatted result. See Printf.failwithf (link: ) for examples. Print to a string using the given format. The formatter. The formatted result. See Printf.sprintf (link: ) for examples. Print to stderr using the given format, and add a newline. The formatter. The formatted result. See Printf.eprintfn (link: ) for examples. Print to stderr using the given format. The formatter. The formatted result. See Printf.eprintf (link: ) for examples. Print to stdout using the given format, and add a newline. The formatter. The formatted result. See Printf.printfn (link: ) for examples. Print to stdout using the given format. The formatter. The formatted result. See Printf.printf (link: ) for examples. Converts the argument to signed byte. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using SByte.Parse() with InvariantCulture settings. Otherwise the operation requires and invokes a ToSByte method on the input type. Checked.int8 -12 Evaluates to -12y. Checked.int8 "129" Throws System.OverflowException. Converts the argument to byte. This is a direct, checked conversion for all primitive numeric types. For strings, the input is converted using Byte.Parse() on strings and otherwise requires a ToByte method on the input type. Checked.uint8 12 Evaluates to -12y. Checked.uint8 -12 Throws System.OverflowException. A set of extra operators and functions. This module is automatically opened in all F# code. Basic Operators