F# – Namespaces

F# – Namespaces ”; Previous Next A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace will not conflict with the same class names declared in another. As per the MSDN library, a namespace lets you organize code into areas of related functionality by enabling you to attach a name to a grouping of program elements. Declaring a Namespace To organize your code in a namespace, you must declare the namespace as the first declaration in the file. The contents of the entire file then become part of the namespace. namespace [parent-namespaces.]identifier The following example illustrates the concept − Example Live Demo namespace testing module testmodule1 = let testFunction x y = printfn “Values from Module1: %A %A” x y module testmodule2 = let testFunction x y = printfn “Values from Module2: %A %A” x y module usermodule = do testmodule1.testFunction ( “one”, “two”, “three” ) 150 testmodule2.testFunction (seq { for i in 1 .. 10 do yield i * i }) 200 When you compile and execute the program, it yields the following output − Values from Module1: (“one”, “two”, “three”) 150 Values from Module2: seq [1; 4; 9; 16; …] 200 Print Page Previous Next Advertisements ”;

F# – Records

F# – Records ”; Previous Next A record is similar to a tuple, however it contains named fields. For example, type website = { title : string; url : string } Defining Record A record is defined as a type using the type keyword, and the fields of the record are defined as a semicolon-separated list. Syntax for defining a record is − type recordName = { [ fieldName : dataType ] + } Creating a Record You can create a record by specifying the record”s fields. For example, let us create a website record named homepage − let homepage = { Title = “TutorialsPoint”; Url = “www.tutorialspoint.com” } The following examples will explain the concepts − Example 1 This program defines a record type named website. Then it creates some records of type website and prints the records. Live Demo (* defining a record type named website *) type website = { Title : string; Url : string } (* creating some records *) let homepage = { Title = “TutorialsPoint”; Url = “www.tutorialspoint.com” } let cpage = { Title = “Learn C”; Url = “www.tutorialspoint.com/cprogramming/index.htm” } let fsharppage = { Title = “Learn F#”; Url = “www.tutorialspoint.com/fsharp/index.htm” } let csharppage = { Title = “Learn C#”; Url = “www.tutorialspoint.com/csharp/index.htm” } (*printing records *) (printfn “Home Page: Title: %A n t URL: %A”) homepage.Title homepage.Url (printfn “C Page: Title: %A n t URL: %A”) cpage.Title cpage.Url (printfn “F# Page: Title: %A n t URL: %A”) fsharppage.Title fsharppage.Url (printfn “C# Page: Title: %A n t URL: %A”) csharppage.Title csharppage.Url When you compile and execute the program, it yields the following output − Home Page: Title: “TutorialsPoint” URL: “www.tutorialspoint.com” C Page: Title: “Learn C” URL: “www.tutorialspoint.com/cprogramming/index.htm” F# Page: Title: “Learn F#” URL: “www.tutorialspoint.com/fsharp/index.htm” C# Page: Title: “Learn C#” URL: “www.tutorialspoint.com/csharp/index.htm” Example 2 Live Demo type student = { Name : string; ID : int; RegistrationText : string; IsRegistered : bool } let getStudent name id = { Name = name; ID = id; RegistrationText = null; IsRegistered = false } let registerStudent st = { st with RegistrationText = “Registered”; IsRegistered = true } let printStudent msg st = printfn “%s: %A” msg st let main() = let preRegisteredStudent = getStudent “Zara” 10 let postRegisteredStudent = registerStudent preRegisteredStudent printStudent “Before Registration: ” preRegisteredStudent printStudent “After Registration: ” postRegisteredStudent main() When you compile and execute the program, it yields the following output − Before Registration: : {Name = “Zara”; ID = 10; RegistrationText = null; IsRegistered = false;} After Registration: : {Name = “Zara”; ID = 10; RegistrationText = “Registered”; IsRegistered = true;} Print Page Previous Next Advertisements ”;

F# – Arrays

F# – Arrays ”; Previous Next Arrays are fixed-size, zero-based, mutable collections of consecutive data elements that are all of the same type. Creating Arrays You can create arrays using various syntaxes and ways or by using the functions from the Array module. In this section, we will discuss creating arrays without using the module functions. There are three syntactical ways of creating arrays without functions − By listing consecutive values between [| and |] and separated by semicolons. By putting each element on a separate line, in which case the semicolon separator is optional. By using sequence expressions. You can access array elements by using a dot operator (.) and brackets ([ and ]). The following example demonstrates creating arrays − Live Demo //using semicolon separator let array1 = [| 1; 2; 3; 4; 5; 6 |] for i in 0 .. array1.Length – 1 do printf “%d ” array1.[i] printfn” ” // without semicolon separator let array2 = [| 1 2 3 4 5 |] for i in 0 .. array2.Length – 1 do printf “%d ” array2.[i] printfn” ” //using sequence let array3 = [| for i in 1 .. 10 -> i * i |] for i in 0 .. array3.Length – 1 do printf “%d ” array3.[i] printfn” ” When you compile and execute the program, it yields the following output − 1 2 3 4 5 6 1 2 3 4 5 1 4 9 16 25 36 49 64 81 100 Basic Operations on Arrays The library module Microsoft.FSharp.Collections.Array supports operations on one-dimensional arrays. The following table shows the basic operations on Arrays − Value Description append : ”T [] → ”T [] → ”T [] Creates an array that contains the elements of one array followed by the elements of another array. average : ^T [] → ^T Returns the average of the elements in an array. averageBy : (”T → ^U) → ”T [] → ^U Returns the average of the elements generated by applying a function to each element of an array. blit : ”T [] → int → ”T [] → int → int → unit Reads a range of elements from one array and writes them into another. choose : (”T → U option) → ”T [] → ”U [] Applies a supplied function to each element of an array. Returns an array that contains the results x for each element for which the function returns Some(x). collect : (”T → ”U []) → T [] → ”U [] Applies the supplied function to each element of an array, concatenates the results, and returns the combined array. concat : seq<”T []> → ”T [] Creates an array that contains the elements of each of the supplied sequence of arrays. copy : ”T → ”T [] Creates an array that contains the elements of the supplied array. create : int → ”T → ”T [] Creates an array whose elements are all initially the supplied value. empty : ”T [] Returns an empty array of the given type. exists : (”T → bool) → ”T [] → bool Tests whether any element of an array satisfies the supplied predicate. exists2 : (”T1 → ”T2 → bool) → ”T1 [] → ”T2 [] → bool Tests whether any pair of corresponding elements of two arrays satisfy the supplied condition. fill : ”T [] → int → int → ”T → unit Fills a range of elements of an array with the supplied value. filter : (”T → bool) → ”T [] → ”T [] Returns a collection that contains only the elements of the supplied array for which the supplied condition returns true. find : (”T → bool) → ”T [] → ”T Returns the first element for which the supplied function returns true. Raises KeyNotFoundException if no such element exists. findIndex : (”T → bool) → ”T [] → int Returns the index of the first element in an array that satisfies the supplied condition. Raises KeyNotFoundException if none of the elements satisfy the condition. fold : (”State → ”T → ”State) → ”State → ”T [] → ”State Applies a function to each element of an array, threading an accumulator argument through the computation. If the input function is f and the array elements are i0…iN, this function computes f (…(f s i0)…) iN. fold2 : (”State → ”T1 → ”T2 → ”State) → ”State → ”T1 [] → ”T2 [] → ”State Applies a function to pairs of elements from two supplied arrays, left-to-right, threading an accumulator argument through the computation. The two input arrays must have the same lengths; otherwise, ArgumentException is raised. foldBack : (”T → ”State → ”State) → ”T [] → ”State → ”State Applies a function to each element of an array, threading an accumulator argument through the computation. If the input function is f and the array elements are i0…iN, this function computes f i0 (…(f iN s)). foldBack2 : (”T1 → ”T2 → ”State → ”State) → ”T1 [] → ”T2 [] → ”State → ”State Applies a function to pairs of elements from two supplied arrays, right-to-left, threading an accumulator argument through the computation. The two input arrays must have the same lengths; otherwise, ArgumentException is raised. forall : (”T → bool) → ”T [] → bool Tests whether all elements of an array satisfy the supplied condition. forall2 : (”T1 → ”T2 → bool) → ”T1 [] → ”T2 [] → bool Tests whether all corresponding elements of two supplied arrays satisfy a supplied condition. get : ”T [] → int → ”T Gets an element from an array. init : int → (int → ”T) → ”T [] Uses a supplied function to create an array of the supplied dimension. isEmpty : ”T [] → bool Tests whether an array has any elements. iter : (”T → unit) → ”T [] → unit Applies the supplied function to each element of an array.

F# – Maps

F# – Maps ”; Previous Next In F#, a map is a special kind of set that associates the values with key. A map is created in a similar way as sets are created. Creating Maps Maps are created by creating an empty map using Map.empty and adding items using the Add function. The following example demonstrates this − Example Live Demo (* Create an empty Map *) let students = Map.empty. (* Creating an empty Map *) Add(“Zara Ali”, “1501”). Add(“Rishita Gupta”, “1502”). Add(“Robin Sahoo”, “1503”). Add(“Gillian Megan”, “1504”);; printfn “Map – students: %A” students (* Convert a list to Map *) let capitals = [ “Argentina”, “Buenos Aires”; “France “, “Paris”; “Chili”, “Santiago”; “Malaysia”, ” Kuala Lumpur”; “Switzerland”, “Bern” ] |> Map.ofList;; printfn “Map capitals : %A” capitals When you compile and execute the program, it yields the following output − Map – students: map [(“Gillian Megan”, “1504”); (“Rishita Gupta”, “1502”); (“Robin Sahoo”, “1503 “); (“Zara Ali”, “1501”)] Map capitals : map [(“Argentina”, “Buenos Aires”); (“Chili”, “Santiago”); (“France “, “Paris”); (“Malaysia”, ” Kuala Lumpur”); (“Switzerland”, “Bern”)] You can access individual elements in the map using the key. Example Live Demo (* Create an empty Map *) let students = Map.empty. (* Creating an empty Map *) Add(“Zara Ali”, “1501”). Add(“Rishita Gupta”, “1502”). Add(“Robin Sahoo”, “1503”). Add(“Gillian Megan”, “1504”);; printfn “Map – students: %A” students (*Accessing an element using key *) printfn “%A” students.[“Zara Ali”] When you compile and execute the program, it yields the following output − Map – students: map [(“Gillian Megan”, “1504”); (“Rishita Gupta”, “1502”); (“Robin Sahoo”, “1503 “); (“Zara Ali”, “1501”)] “1501” Basic Operations on Maps Add module name The following table shows the basic operations on maps − Member Description Add Returns a new map with the binding added to the given map. ContainsKey Tests if an element is in the domain of the map. Count The number of bindings in the map. IsEmpty Returns true if there are no bindings in the map. Item Lookup an element in the map. Raises KeyNotFoundException if no binding exists in the map. Remove Removes an element from the domain of the map. No exception is raised if the element is not present. TryFind 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 following example demonstrates the uses of some of the above functionalities − Example Live Demo (* Create an empty Map *) let students = Map.empty. (* Creating an empty Map *) Add(“Zara Ali”, “1501”). Add(“Rishita Gupta”, “1502”). Add(“Robin Sahoo”, “1503”). Add(“Gillian Megan”, “1504”). Add(“Shraddha Dubey”, “1505”). Add(“Novonil Sarker”, “1506”). Add(“Joan Paul”, “1507”);; printfn “Map – students: %A” students printfn “Map – number of students: %d” students.Count (* finding the registration number of a student*) let found = students.TryFind “Rishita Gupta” match found with | Some x -> printfn “Found %s.” x | None -> printfn “Did not find the specified value.” When you compile and execute the program, it yields the following output − Map – students: map [(“Gillian Megan”, “1504”); (“Joan Paul”, “1507”); (“Novonil Sarker”, “1506” ); (“Rishita Gupta”, “1502”); (“Robin Sahoo”, “1503”); (“Shraddha Dubey”, “1505”); (“Zara Ali”, “1501”)] Map – number of students: 7 Found 1502. Print Page Previous Next Advertisements ”;

F# – Program Structure

F# – Program Structure ”; Previous Next F# is a Functional Programming language. In F#, functions work like data types. You can declare and use a function in the same way like any other variable. In general, an F# application does not have any specific entry point. The compiler executes all top-level statements in the file from top to bottom. However, to follow procedural programming style, many applications keep a single top level statement that calls the main loop. The following code shows a simple F# program − Live Demo open System (* This is a multi-line comment *) // This is a single-line comment let sign num = if num > 0 then “positive” elif num < 0 then “negative” else “zero” let main() = Console.WriteLine(“sign 5: {0}”, (sign 5)) main() When you compile and execute the program, it yields the following output − sign 5: positive Please note that − An F# code file might begin with a number of open statements that is used to import namespaces. The body of the files includes other functions that implement the business logic of the application. The main loop contains the top executable statements. Print Page Previous Next Advertisements ”;

F# – Overview

F# – Overview ”; Previous Next F# is a functional programming language. To understand F# constructs, you need to read a couple of lines about the programming paradigm named Functional Programming. Functional programming treats computer programs as mathematical functions. In functional programming, the focus would be on constants and functions, instead of variables and states. Because functions and constants are things that don’t change. In functional programming, you will write modular programs, i.e., the programs would consist of functions that will take other functions as input. Programs written in functional programming language tend to be concise. About F# Following are the basic information about F# − It was developed in 2005 at Microsoft Research. It is a part of Microsoft’s family of .Net language. It is a functional programming language. It is based on the functional programming language OCaml. Features of F# It is .Net implementation of OCaml. It compiles .Net CLI (Common Language Interface) byte code or MSIL (Microsoft Intermediate Language) that runs on CLR (Common Language Runtime). It provides type inference. It provides rich pattern matching constructs. It has interactive scripting and debugging capabilities. It allows writing higher order functions. It provides well developed object model. Use of F# F# is normally used in the following areas − Making scientific model Mathematical problem solving Artificial intelligence research work Financial modelling Graphic design CPU design Compiler programming Telecommunications It is also used in CRUD apps, web pages, GUI games and other general purpose programs. Print Page Previous Next Advertisements ”;

F# – Delegates

F# – Delegates ”; Previous Next A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. F# delegates are similar to pointers to functions, in C or C++. Declaring Delegates Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which have the same signature as that of the delegate. Syntax for delegate declaration is − type delegate-typename = delegate of type1 -> type2 For example, consider the delegates − // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int Both the delegates can be used to reference any method that has two int parameters and returns an int type variable. In the syntax − type1 represents the argument type(s). type2 represents the return type. Please note − The argument types are automatically curried. Delegates can be attached to function values, and static or instance methods. F# function values can be passed directly as arguments to delegate constructors. For a static method the delegate is called by using the name of the class and the method. For an instance method, the name of the object instance and method is used. The Invoke method on the delegate type calls the encapsulated function. Also, delegates can be passed as function values by referencing the Invoke method name without the parentheses. The following example demonstrates the concept − Example Live Demo type Myclass() = static member add(a : int, b : int) = a + b static member sub (a : int) (b : int) = a – b member x.Add(a : int, b : int) = a + b member x.Sub(a : int) (b : int) = a – b // Delegate1 works with tuple arguments. type Delegate1 = delegate of (int * int) -> int // Delegate2 works with curried arguments. type Delegate2 = delegate of int * int -> int let InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) = dlg.Invoke(a, b) let InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) = dlg.Invoke(a, b) // For static methods, use the class name, the dot operator, and the // name of the static method. let del1 : Delegate1 = new Delegate1( Myclass.add ) let del2 : Delegate2 = new Delegate2( Myclass.sub ) let mc = Myclass() // For instance methods, use the instance value name, the dot operator, // and the instance method name. let del3 : Delegate1 = new Delegate1( mc.Add ) let del4 : Delegate2 = new Delegate2( mc.Sub ) for (a, b) in [ (400, 200); (100, 45) ] do printfn “%d + %d = %d” a b (InvokeDelegate1 del1 a b) printfn “%d – %d = %d” a b (InvokeDelegate2 del2 a b) printfn “%d + %d = %d” a b (InvokeDelegate1 del3 a b) printfn “%d – %d = %d” a b (InvokeDelegate2 del4 a b) When you compile and execute the program, it yields the following output − 400 + 200 = 600 400 – 200 = 200 400 + 200 = 600 400 – 200 = 200 100 + 45 = 145 100 – 45 = 55 100 + 45 = 145 100 – 45 = 55 Print Page Previous Next Advertisements ”;

F# – Operators

F# – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. F# is rich in built-in operators and provides the following types of operators − Arithmetic Operators Comparison Operators Boolean Operators Bitwise Operators Arithmetic Operators The following table shows all the arithmetic operators supported by F# language. Assume variable A holds 10 and variable B holds 20 then − Show Example Operator Description Example + Adds two operands A + B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0 ** Exponentiation Operator, raises an operand to the power of another B**A will give 2010 Comparison Operators The following table shows all the comparison operators supported by F# language. These binary comparison operators are available for integral and floating-point types. These operators return values of type bool. Assume variable A holds 10 and variable B holds 20, then − Show Example Operator Description Example = Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. <> Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A <> B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Boolean Operators The following table shows all the Boolean operators supported by F# language. Assume variable A holds true and variable B holds false, then − Show Example Operator Description Example && Called Boolean AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. || Called Boolean OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. not Called Boolean NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. not (A && B) is true. Bitwise Operators Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &&& (bitwise AND), ||| (bitwise OR), and ^^^ (bitwise exclusive OR) are as follows − Show Example p q p &&& q p ||| q p ^^^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 —————– A&&&B = 0000 1100 A|||B = 0011 1101 A^^^B = 0011 0001 ~~~A = 1100 0011 The Bitwise operators supported by F# language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then − Operator Description Example &&& Binary AND Operator copies a bit to the result if it exists in both operands. (A &&& B) will give 12, which is 0000 1100 ||| Binary OR Operator copies a bit if it exists in either operand. (A ||| B) will give 61, which is 0011 1101 ^^^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^^^ B) will give 49, which is 0011 0001 ~~~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~~~A) will give -61, which is 1100 0011 in 2”s complement form. <<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A <<< 2 will give 240 which is 1111 0000 >>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >>> 2 will give 15 which is 0000 1111 Operators Precedence The following table shows the order of precedence of operators and other expression keywords in the F# language, from lowest precedence to the highest precedence. Show Example Operator Associativity as Right when Right | (pipe) Left ; Right let Non associative function, fun, match, try Non associative if Non associative → Right := Right , Non associative or, || Left &, && Left < op, >op, =, |op, &op Left &&& , |||, ^^^, ~~~, <<<, >>> Left ^ op Right :: Right :?>, 😕 Non associative – op, +op, (binary) Left * op, /op, %op Left ** op Right f x (function application) Left | (pattern match) Right prefix operators (&plus;op, -op, %, %%, &, &&, !op, ~op) Left . Left f(x) Left f<types> Left Print Page Previous Next Advertisements ”;

F# – Data Types

F# – Data Types ”; Previous Next The data types in F# can be classified as follows − Integral types Floating point types Text types Other types Integral Data Type The following table provides the integral data types of F#. These are basically integer data types. F# Type Size Range Example Remarks sbyte 1 byte -128 to 127 42y -11y 8-bit signed integer byte 1 byte 0 to 255 42uy 200uy 8-bit unsigned integer int16 2 bytes -32768 to 32767 42s -11s 16-bit signed integer uint16 2 bytes 0 to 65,535 42us 200us 16-bit unsigned integer int/int32 4 bytes -2,147,483,648 to 2,147,483,647 42 -11 32-bit signed integer uint32 4 bytes 0 to 4,294,967,295 42u 200u 32-bit unsigned integer int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 42L -11L 64-bit signed integer uint64 8 bytes 0 to 18,446,744,073,709,551,615 42UL 200UL 64-bit unsigned integer bigint At least 4 bytes any integer 42I 1499999 9999999 9999999 9999999 9999I arbitrary precision integer Example Live Demo (* single byte integer *) let x = 268.97f let y = 312.58f let z = x + y printfn “x: %f” x printfn “y: %f” y printfn “z: %f” z (* unsigned 8-bit natural number *) let p = 2uy let q = 4uy let r = p + q printfn “p: %i” p printfn “q: %i” q printfn “r: %i” r (* signed 16-bit integer *) let a = 12s let b = 24s let c = a + b printfn “a: %i” a printfn “b: %i” b printfn “c: %i” c (* signed 32-bit integer *) let d = 212l let e = 504l let f = d + e printfn “d: %i” d printfn “e: %i” e printfn “f: %i” f When you compile and execute the program, it yields the following output − x: 1 y: 2 z: 3 p: 2 q: 4 r: 6 a: 12 b: 24 c: 36 d: 212 e: 504 f: 716 Floating Point Data Types The following table provides the floating point data types of F#. F# Type Size Range Example Remarks float32 4 bytes ±1.5e-45 to ±3.4e38 42.0F -11.0F 32-bit signed floating point number (7 significant digits) float 8 bytes ±5.0e-324 to ±1.7e308 42.0 -11.0 64-bit signed floating point number (15-16 significant digits) decimal 16 bytes ±1.0e-28 to ±7.9e28 42.0M -11.0M 128-bit signed floating point number (28-29 significant digits) BigRational At least 4 bytes Any rational number. 42N -11N Arbitrary precision rational number. Using this type requires a reference to FSharp.PowerPack.dll. Example Live Demo (* 32-bit signed floating point number *) (* 7 significant digits *) let d = 212.098f let e = 504.768f let f = d + e printfn “d: %f” d printfn “e: %f” e printfn “f: %f” f (* 64-bit signed floating point number *) (* 15-16 significant digits *) let x = 21290.098 let y = 50446.768 let z = x + y printfn “x: %g” x printfn “y: %g” y printfn “z: %g” z When you compile and execute the program, it yields the following output − d: 212.098000 e: 504.768000 f: 716.866000 x: 21290.1 y: 50446.8 z: 71736.9 Text Data Types The following table provides the text data types of F#. F# Type Size Range Example Remarks char 2 bytes U+0000 to U+ffff ”x” ”t” Single unicode characters string 20 + (2 * string”s length) bytes 0 to about 2 billion characters “Hello” “World” Unicode text Example Live Demo let choice = ”y” let name = “Zara Ali” let org = “Tutorials Point” printfn “Choice: %c” choice printfn “Name: %s” name printfn “Organisation: %s” org When you compile and execute the program, it yields the following output − Choice: y Name: Zara Ali Organisation: Tutorials Point Other Data Types The following table provides some other data types of F#. F# Type Size Range Example Remarks bool 1 byte Only two possible values, true or false true false Stores boolean values Example Live Demo let trueVal = true let falseVal = false printfn “True Value: %b” (trueVal) printfn “False Value: %b” (falseVal) When you compile and execute the program, it yields the following output − True Value: true False Value: false Print Page Previous Next Advertisements ”;

F# – Mutable Data

F# – Mutable Data ”; Previous Next Variables in F# are immutable, which means once a variable is bound to a value, it can’t be changed. They are actually compiled as static read-only properties. The following example demonstrates this. Example Live Demo let x = 10 let y = 20 let z = x + y printfn “x: %i” x printfn “y: %i” y printfn “z: %i” z let x = 15 let y = 20 let z = x + y printfn “x: %i” x printfn “y: %i” y printfn “z: %i” z When you compile and execute the program, it shows the following error message − Duplicate definition of value ”x” Duplicate definition of value ”Y” Duplicate definition of value ”Z” Mutable Variables At times you need to change the values stored in a variable. To specify that there could be a change in the value of a declared and assigned variable in later part of a program, F# provides the mutable keyword. You can declare and assign mutable variables using this keyword, whose values you will change. The mutable keyword allows you to declare and assign values in a mutable variable. You can assign some initial value to a mutable variable using the let keyword. However, to assign new subsequent value to it, you need to use the <- operator. For example, let mutable x = 10 x <- 15 The following example will clear the concept − Example Live Demo let mutable x = 10 let y = 20 let mutable z = x + y printfn “Original Values:” printfn “x: %i” x printfn “y: %i” y printfn “z: %i” z printfn “Let us change the value of x” printfn “Value of z will change too.” x <- 15 z <- x + y printfn “New Values:” printfn “x: %i” x printfn “y: %i” y printfn “z: %i” z When you compile and execute the program, it yields the following output − Original Values: x: 10 y: 20 z: 30 Let us change the value of x Value of z will change too. New Values: x: 15 y: 20 z: 35 Uses of Mutable Data Mutable data is often required and used in data processing, particularly with record data structure. The following example demonstrates this − Live Demo open System type studentData = { ID : int; mutable IsRegistered : bool; mutable RegisteredText : string; } let getStudent id = { ID = id; IsRegistered = false; RegisteredText = null; } let registerStudents (students : studentData list) = students |> List.iter(fun st -> st.IsRegistered <- true st.RegisteredText <- sprintf “Registered %s” (DateTime.Now.ToString(“hh:mm:ss”)) Threading.Thread.Sleep(1000) (* Putting thread to sleep for 1 second to simulate processing overhead. *)) let printData (students : studentData list) = students |> List.iter (fun x -> printfn “%A” x) let main() = let students = List.init 3 getStudent printfn “Before Process:” printData students printfn “After process:” registerStudents students printData students Console.ReadKey(true) |> ignore main() When you compile and execute the program, it yields the following output − Before Process: {ID = 0; IsRegistered = false; RegisteredText = null;} {ID = 1; IsRegistered = false; RegisteredText = null;} {ID = 2; IsRegistered = false; RegisteredText = null;} After process: {ID = 0; IsRegistered = true; RegisteredText = “Registered 05:39:15”;} {ID = 1; IsRegistered = true; RegisteredText = “Registered 05:39:16”;} {ID = 2; IsRegistered = true; RegisteredText = “Registered 05:39:17″;} Print Page Previous Next Advertisements ”;