F# – Mutable Lists

F# – Mutable Lists ”; Previous Next The List<”T> class represents a strongly typed list of objects that can be accessed by index. It is a mutable counterpart of the List class. It is similar to arrays, as it can be accessed by an index, however, unlike arrays, lists can be resized. Therefore you need not specify a size during declaration. Creating a Mutable List Lists are created using the new keyword and calling the list”s constructor. The following example demonstrates this − Live Demo (* Creating a List *) open System.Collections.Generic let booksList = new List<string>() booksList.Add(“Gone with the Wind”) booksList.Add(“Atlas Shrugged”) booksList.Add(“Fountainhead”) booksList.Add(“Thornbirds”) booksList.Add(“Rebecca”) booksList.Add(“Narnia”) booksList |> Seq.iteri (fun index item -> printfn “%i: %s” index booksList.[index]) When you compile and execute the program, it yields the following output − 0: Gone with the Wind 1: Atlas Shrugged 2: Fountainhead 3: Thornbirds 4: Rebecca 5: Narnia The List(T) Class The List(T) class represents a strongly typed list of objects that can be accessed by index. It provide methods to search, sort, and manipulate lists. The following tables provide the properties, constructors and the methods of the List(T) class − Properties Property Description Capacity Gets or sets the total number of elements the internal data structure can hold without resizing. Count Gets the number of elements contained in the List(T). Item Gets or sets the element at the specified index. Constructors Constructor Description List(T)() Initializes a new instance of the List(T) class that is empty and has the default initial capacity. List(T)(IEnumerable(T)) Initializes a new instance of the List(T) class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied. List(T)(Int32) Initializes a new instance of the List(T) class that is empty and has the specified initial capacity. Method Methods Description Add Adds an object to the end of the List(T). AddRange Adds the elements of the specified collection to the end of the List(T). AsReadOnly Returns a read-only IList(T) wrapper for the current collection. BinarySearch(T) Searches the entire sorted List(T) for an element using the default comparer and returns the zero-based index of the element. BinarySearch(T, IComparer(T)) Searches the entire sorted List(T) for an element using the specified comparer and returns the zero-based index of the element. BinarySearch(Int32, Int32, T, IComparer(T)) Searches a range of elements in the sorted List(T) for an element using the specified comparer and returns the zero-based index of the element. Clear Removes all elements from the List(T). Contains Determines whether an element is in the List(T). ConvertAll(TOutput) Converts the elements in the current List(T) to another type, and returns a list containing the converted elements. CopyTo(T[]) Copies the entire List(T) to a compatible one-dimensional array, starting at the beginning of the target array. CopyTo(T[], Int32) Copies the entire List(T) to a compatible one-dimensional array, starting at the specified index of the target array. CopyTo(Int32, T[], Int32, Int32) Copies a range of elements from the List(T) to a compatible one-dimensional array, starting at the specified index of the target array. Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object.) Exists Determines whether the List(T) contains elements that match the conditions defined by the specified predicate. Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection (Inherited from Object). Find Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List(T). FindAll Retrieves all the elements that match the conditions defined by the specified predicate. FindIndex(Predicate(T)) Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List(T). FindIndex(Int32, Predicate(T)) Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List(T) that extends from the specified index to the last element. FindIndex(Int32, Int32, Predicate(T)) Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List(T) that starts at the specified index and contains the specified number of elements. FindLast Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire List(T). FindLastIndex(Predicate(T)) Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire List(T). FindLastIndex(Int32, Predicate(T)) Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List(T) that extends from the first element to the specified index. FindLastIndex(Int32, Int32, Predicate(T)) Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List(T) that contains the specified number of elements and ends at the specified index. ForEach Performs the specified action on each element of the List(T). GetEnumerator Returns an enumerator that iterates through the List(T). GetHashCode Serves as the default hash function. (Inherited from Object.) GetRange Creates a shallow copy of a range of elements in the source List(T). GetType Gets the Type of the current instance. (Inherited from Object.) IndexOf(T) Searches for the specified object and returns the zero-based index of the first occurrence within the entire List(T). IndexOf(T, Int32) Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List(T) that extends from the specified index to the last element. IndexOf(T, Int32, Int32) Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List(T) that starts at the specified index and contains the specified number of elements.

F# – Sequences

F# – Sequences ”; Previous Next Sequences, like lists also represent an ordered collection of values. However, the elements in a sequence or sequence expression are computed when required. They are not computed at once, and for this reason they are used to represent infinite data structures. Defining Sequences Sequences are defined using the following syntax − seq { expr } For example, let seq1 = seq { 1 .. 10 } Creating Sequences and Sequences Expressions Similar to lists, you can create sequences using ranges and comprehensions. Sequence expressions are the expressions you can write for creating sequences. These can be done − By specifying the range. By specifying the range with increment or decrement. By using the yield keyword to produce values that become part of the sequence. By using the → operator. The following examples demonstrate the concept − Example 1 Live Demo (* Sequences *) let seq1 = seq { 1 .. 10 } (* ascending order and increment*) printfn “The Sequence: %A” seq1 let seq2 = seq { 1 .. 5 .. 50 } (* descending order and decrement*) printfn “The Sequence: %A” seq2 let seq3 = seq {50 .. -5 .. 0} printfn “The Sequence: %A” seq3 (* using yield *) let seq4 = seq { for a in 1 .. 10 do yield a, a*a, a*a*a } printfn “The Sequence: %A” seq4 When you compile and execute the program, it yields the following output − The Sequence: seq [1; 2; 3; 4; …] The Sequence: seq [1; 6; 11; 16; …] The Sequence: seq [50; 45; 40; 35; …] The Sequence: seq [(1, 1, 1); (2, 4, 8); (3, 9, 27); (4, 16, 64); …] Example 2 The following program prints the prime numbers from 1 to 50 − Live Demo (* Recursive isprime function. *) let isprime n = let rec check i = i > n/2 || (n % i <> 0 && check (i + 1)) check 2 let primeIn50 = seq { for n in 1..50 do if isprime n then yield n } for x in primeIn50 do printfn “%d” x When you compile and execute the program, it yields the following output − 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Basic Operations on Sequence The following table shows the basic operations on sequence data type − Value Description append : seq<”T> → seq<”T> → seq<”T> Wraps the two given enumerations as a single concatenated enumeration. average : seq<^T> → ^T Returns the average of the elements in the sequence. averageBy : (”T → ^U) → seq<”T> → ^U Returns the average of the results generated by applying the function to each element of the sequence. cache : seq<”T> → seq<”T> Returns a sequence that corresponds to a cached version of the input sequence. cast : IEnumerable → seq<”T> Wraps a loosely-typed System. Collections sequence as a typed sequence. choose : (”T → ”U option) → seq<”T> → seq<”U> Applies the given function to each element of the list. Return the list comprised of the results for each element where the function returns Some. collect : (”T → ”Collection) → seq<”T> → seq<”U> Applies the given function to each element of the sequence and concatenates all the results. compareWith : (”T → ”T → int) → seq<”T> → seq<”T> → int Compares two sequences using the given comparison function, element by element. concat : seq<”Collection> → seq<”T> Combines the given enumeration-of-enumerations as a single concatenated enumeration. countBy : (”T → ”Key) → seq<”T> → seq<”Key * int> Applies a key-generating function to each element of a sequence and return a sequence yielding unique keys and their number of occurrences in the original sequence. delay : (unit → seq<”T>) → seq<”T> Returns a sequence that is built from the given delayed specification of a sequence. distinct : seq<”T> → seq<”T> 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. distinctBy : (”T → ”Key) → seq<”T> → seq<”T> 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. empty : seq<”T> Creates an empty sequence. exactlyOne : seq<”T> → ”T Returns the only element of the sequence. exists : (”T → bool) → seq<”T> → bool Tests if any element of the sequence satisfies the given predicate. exists2 : (”T1 → ”T2 → bool) → seq<”T1> → seq<”T2> → bool Tests if any pair of corresponding elements of the input sequences satisfies the given predicate. filter : (”T → bool) → seq<”T> → seq<”T> Returns a new collection containing only the elements of the collection for which the given predicate returns true. find : (”T → bool) → seq<”T> → ”T Returns the first element for which the given function returns true. findIndex : (”T → bool) → seq<”T> → int Returns the index of the first element for which the given function returns true. fold : (”State → ”T → ”State) → ”State → seq<”T> → ”State 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 this function computes f (… (f s i0)…) iN. forall : (”T → bool) → seq<”T> → bool Tests if all elements of the sequence satisfy the given predicate. forall2 : (”T1 → ”T2 → bool) → seq<”T1> → seq<”T2> → bool 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. groupBy : (”T → ”Key) → seq<”T> → seq<”Key * seq<”T>>

F# – Sets

F# – Sets ”; Previous Next A set in F# is a data structure that acts as a collection of items without preserving the order in which items are inserted. Sets do not allow duplicate entries to be inserted into the collection. Creating Sets Sets can be created in the following ways − By creating an empty set using Set.empty and adding items using the add function. Converting sequences and lists to sets. The following program demonstrates the techniques − Live Demo (* creating sets *) let set1 = Set.empty.Add(3).Add(5).Add(7). Add(9) printfn”The new set: %A” set1 let weekdays = Set.ofList [“mon”; “tues”; “wed”; “thurs”; “fri”] printfn “The list set: %A” weekdays let set2 = Set.ofSeq [ 1 .. 2.. 10 ] printfn “The sequence set: %A” set2 When you compile and execute the program, it yields the following output − The new set: set [3; 5; 7; 9] The list set: set [“fri”; “mon”; “thurs”; “tues”; “wed”] The sequence set: set [1; 3; 5; 7; 9] Basic Operations on Sets The following table shows the basic operations on sets − Value Description add : ”T → Set<”T> → Set<”T> Returns a new set with an element added to the set. No exception is raised if the set already contains the given element. contains : ”T → Set<”T> → bool Evaluates to true if the given element is in the given set. count : Set<”T> → int Returns the number of elements in the set. difference : Set<”T> → Set<”T> → Set<”T> Returns a new set with the elements of the second set removed from the first. empty : Set<”T> The empty set for the specified type. exists : (”T → bool) → Set<”T> → bool Tests if any element of the collection satisfies the given predicate. If the input function is predicate and the elements are i0…iN, then this function computes predicate i0 or … or predicate iN. filter : (”T → bool) → Set<”T> → Set<”T> Returns a new collection containing only the elements of the collection for which the given predicate returns true. fold : (”State → ”T → ”State) → ”State → Set<”T> → ”State Applies the given accumulating function to all the elements of the set. foldBack : (”T → ”State → ”State) → Set<”T> → ”State → ”State Applies the given accumulating function to all the elements of the set. forall : (”T → bool) → Set<”T> → bool Tests if all elements of the collection satisfy the given predicate. If the input function is p and the elements are i0…iN, then this function computes p i0 && … && p iN. intersect : Set<”T> → Set<”T> → Set<”T> Computes the intersection of the two sets. intersectMany : seq<Set<”T>> → Set<”T> Computes the intersection of a sequence of sets. The sequence must be non-empty. isEmpty : Set<”T> → bool Returns true if the set is empty. isProperSubset : Set<”T> → Set<”T> → bool 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. isProperSuperset : Set<”T> → Set<”T> → bool 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. isSubset : Set<”T> → Set<”T> → bool Evaluates to true if all elements of the first set are in the second. isSuperset : Set<”T> → Set<”T> → bool Evaluates to true if all elements of the second set are in the first. iter : (”T → unit) → Set<”T> → unit Applies the given function to each element of the set, in order according to the comparison function. map : (”T → ”U) → Set<”T> → Set<”U> Returns a new collection containing the results of applying the given function to each element of the input set. maxElement : Set<”T> → ”T Returns the highest element in the set according to the ordering being used for the set. minElement : Set<”T> → ”T Returns the lowest element in the set according to the ordering being used for the set. ofArray : ”T array → Set<”T> Creates a set that contains the same elements as the given array. ofList : ”T list → Set<”T> Creates a set that contains the same elements as the given list. ofSeq : seq<”T> → Set<”T> Creates a new collection from the given enumerable object. partition : (”T → bool) → Set<”T> → Set<”T> * Set<”T> Splits the set into two sets containing the elements for which the given predicate returns true and false respectively. remove : ”T → Set<”T> → Set<”T> Returns a new set with the given element removed. No exception is raised if the set doesn”t contain the given element. singleton : ”T → Set<”T> The set containing the given element. toArray : Set<”T> → ”T array Creates an array that contains the elements of the set in order. toList : Set<”T> → ”T list Creates a list that contains the elements of the set in order. toSeq : Set<”T> → seq<”T> Returns an ordered view of the collection as an enumerable object. union : Set<”T> → Set<”T> → Set<”T> Computes the union of the two sets. unionMany : seq<Set<”T>> → Set<”T> Computes the union of a sequence of sets. The following example demonstrates the uses of some of the above functionalities − Example Live Demo let a = Set.ofSeq [ 1 ..2.. 20 ] let b = Set.ofSeq [ 1 ..3 .. 20 ] let c = Set.intersect a b let d = Set.union a b let e = Set.difference a b printfn “Set a: ” Set.iter (fun x -> printf “%O ” x) a printfn”” printfn “Set b: ” Set.iter (fun x -> printf “%O ” x) b printfn”” printfn “Set c = set intersect of a and b : ” Set.iter (fun x -> printf “%O ” x) c printfn”” printfn “Set d = set union of a

F# – Mutable Dictionary

F# – Mutable Dictionary ”; Previous Next The Dictionary<”TKey, ”TValue> class is the mutable analog of the F# map data structure and contains many of the same functions. Recapitulating from the Map chapter in F#, a map is a special kind of set that associates the values with key. Creating of a Mutable Dictionary Mutable dictionaries are created using the new keyword and calling the list”s constructor. The following example demonstrates this − Live Demo open System.Collections.Generic let dict = new Dictionary<string, string>() dict.Add(“1501”, “Zara Ali”) dict.Add(“1502″,”Rishita Gupta”) dict.Add(“1503″,”Robin Sahoo”) dict.Add(“1504″,”Gillian Megan”) printfn “Dictionary – students: %A” dict When you compile and execute the program, it yields the following output − Dictionary – students: seq [[1501, Zara Ali]; [1502, Rishita Gupta]; [1503, Robin Sahoo]; [1504, Gillian Megan]] The Dictionary(TKey,TValue) Class The Dictionary(TKey, TValue) Class represents a collection of keys and values. The following tables provide the properties, constructors and the methods of the List(T) class − Properties Property Description Comparer Gets the IEqualityComparer(T) that is used to determine equality of keys for the dictionary. Count Gets the number of key/value pairs contained in the Dictionary(TKey, TValue). Item Gets or sets the value associated with the specified key. Keys Gets a collection containing the keys in the Dictionary(TKey, TValue). Values Gets a collection containing the values in the Dictionary(TKey, TValue). Constructors Constructors Description Dictionary(TKey, TValue)() Initializes a new instance of the Dictionary(TKey, TValue) class that is empty, has the default initial capacity, and uses the default equality comparer for the key type. Dictionary(TKey, TValue)(IDictionary(TKey, TValue)) Initializes a new instance of the Dictionary(TKey, TValue) class that contains elements copied from the specified IDictionary(TKey, TValue) and uses the default equality comparer for the key type. Dictionary(TKey, TValue)(IEqualityComparer(TKey)) Initializes a new instance of the Dictionary(TKey, TValue) class that is empty, has the default initial capacity, and uses the specified IEqualityComparer(T). Dictionary(TKey, TValue)(Int32) Initializes a new instance of the Dictionary(TKey, TValue) class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type. Dictionary(TKey, TValue)(IDictionary(TKey, TValue), IEqualityComparer(TKey)) Initializes a new instance of the Dictionary(TKey, TValue) class that contains elements copied from the specified IDictionary(TKey, TValue) and uses the specified IEqualityComparer(T). Dictionary(TKey, TValue)(Int32, IEqualityComparer(TKey)) Initializes a new instance of the Dictionary(TKey, TValue) class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer(T). Dictionary(TKey, TValue)(SerializationInfo, StreamingContext) Initializes a new instance of the ictionary(TKey, TValue) class with serialized data. Methods Method Description Add Adds the specified key and value to the dictionary. Clear Removes all keys and values from the Dictionary(TKey, TValue). ContainsKey Determines whether the Dictionary(TKey, TValue) contains the specified key. ContainsValue Determines whether the Dictionary(TKey, TValue) contains a specific value. Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object.) Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) GetEnumerator Returns an enumerator that iterates through the Dictionary(TKey, TValue). GetHashCode Serves as the default hash function. (Inherited from Object.) GetObjectData Implements the System.Runtime.Serialization.ISerializable interface and returns the data needed to serialize the Dictionary(TKey, TValue)instance. GetType Gets the Type of the current instance. (Inherited from Object.) MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) OnDeserialization Implements the System.Runtime.Serialization.ISerializable interface and raises the deserialization event when the deserialization is complete. Remove Removes the value with the specified key from the Dictionary(TKey, TValue). ToString Returns a string that represents the current object. (Inherited from Object.) TryGetValue Gets the value associated with the specified key. Example Live Demo open System.Collections.Generic let dict = new Dictionary<string, string>() dict.Add(“1501”, “Zara Ali”) dict.Add(“1502″,”Rishita Gupta”) dict.Add(“1503″,”Robin Sahoo”) dict.Add(“1504″,”Gillian Megan”) printfn “Dictionary – students: %A” dict printfn “Total Number of Students: %d” dict.Count printfn “The keys: %A” dict.Keys printf”The Values: %A” dict.Values When you compile and execute the program, it yields the following output − Dictionary – students: seq [[1501, Zara Ali]; [1502, Rishita Gupta]; [1503, Robin Sahoo]; [1504, Gillian Megan]] Total Number of Students: 4 The keys: seq [“1501”; “1502”; “1503”; “1504”] The Values: seq [“Zara Ali”; “Rishita Gupta”; “Robin Sahoo”; “Gillian Megan”] Print Page Previous Next Advertisements ”;

F# – Classes

F# – Classes ”; Previous Next Classes are types that represent objects that can have properties, methods, and events. ‘They are used to model actions, processes, and any conceptual entities in applications’. Syntax Syntax for defining a class type is as follows − // Class definition: type [access-modifier] type-name [type-params] [access-modifier] ( parameter-list ) [ as identifier ] = [ class ] [ inherit base-type-name(base-constructor-args) ] [ let-bindings ] [ do-bindings ] member-list … [ end ] // Mutually recursive class definitions: type [access-modifier] type-name1 … and [access-modifier] type-name2 … … Where, The type-name is any valid identifier. Default access modifier for this is public. The type-params describes optional generic type parameters. The parameter-list describes constructor parameters. Default access modifier for primary constructor is public. The identifier used with the optional as keyword gives a name to the instance variable, or self-identifier, which can be used in the type definition to refer to the instance of the type. The inherit keyword allows you to specify the base class for a class. The let bindings allow you to declare fields or function values local to the class. The do-bindings section includes code to be executed upon object construction. The member-list consists of additional constructors, instance and static method declarations, interface declarations, abstract bindings, and property and event declarations. The keywords class and end that mark the start and end of the definition are optional. Constructor of a Class The constructor is code that creates an instance of the class type. In F#, constructors work little differently than other .Net languages. In the class definition, the arguments of the primary constructor are described as parameter-list. The body of the constructor consists of the let and do bindings. You can add additional constructors by using the new keyword to add a member − new (argument-list) = constructor-body The following example illustrates the concept − Example The following program creates a line class along with a constructor that calculates the length of the line while an object of the class is created − Live Demo type Line = class val X1 : float val Y1 : float val X2 : float val Y2 : float new (x1, y1, x2, y2) as this = { X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;} then printfn ” Creating Line: {(%g, %g), (%g, %g)}nLength: %g” this.X1 this.Y1 this.X2 this.Y2 this.Length member x.Length = let sqr x = x * x sqrt(sqr(x.X1 – x.X2) + sqr(x.Y1 – x.Y2) ) end let aLine = new Line(1.0, 1.0, 4.0, 5.0) When you compile and execute the program, it yields the following output − Creating Line: {(1, 1), (4, 5)} Length: 5 Let Bindings The let bindings in a class definition allow you to define private fields and private functions for F# classes. Live Demo type Greetings(name) as gr = let data = name do gr.PrintMessage() member this.PrintMessage() = printf “Hello %sn” data let gtr = new Greetings(“Zara”) When you compile and execute the program, it yields the following output − Hello Zara Please note the use of self-identifier gr for the Greetings class. Print Page Previous Next Advertisements ”;

F# – Quick Guide

F# – Quick Guide ”; Previous Next F# – Overview 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. F# – Environment Setup The tools required for F# programming are discussed in this chapter. Integrated Development Environment(IDE) for F# Microsoft provides Visual Studio 2013 for F# programming. The free Visual Studio 2013 Community Edition is available from Microsoft’s official website. Visual Studio 2013 Community and above comes with the Visual F# Tools. Installation details available at Asp.net Tutorial .The Visual F# Tools include the command-line compiler (fsc.exe) and F# Interactive (fsi.exe). Using these tools, you can write all kinds of F# programs from simple command-line applications to more complex applications. You can also write F# source code files using a basic text editor, like Notepad, and compile the code into assemblies using the command-line compiler. You can download it from Microsoft Visual Studio. It gets automatically installed in your machine. Writing F# Programs On Links Please visit the F# official website for the latest instructions on getting the tools as a Debian package or compiling them directly from the source − https://fsharp.org/use/linux/. F# – Program Structure 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. F# – Basic Syntax You have seen the basic structure of an F# program, so it will be easy to understand other basic building blocks of the F# programming language. Tokens in F# An F# program consists of various tokens. A token could be a keyword, an identifier, a constant, a string literal, or a symbol. We can categorize F# tokens into two types − Keywords Symbol and Operators F# Keywords The following table shows the keywords and brief descriptions of the keywords. We will discuss the use of these keywords in subsequent chapters. Keyword Description abstract Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation. and Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters. as Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match. assert Used to verify code during debugging. base Used as the name of the base class object. begin In verbose syntax, indicates the start of a code block. class In verbose syntax, indicates the start of a class definition. default Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method. delegate Used to declare a delegate. do Used in looping constructs or to execute imperative code. done In verbose syntax, indicates the end of a block of code in a looping expression. downcast Used to convert to a type that is lower in the inheritance chain. downto In a for expression, used when counting in reverse. elif Used in conditional branching. A short form of else if. else Used in conditional branching. end In type definitions and type extensions, indicates the end of a section of member definitions. In verbose syntax, used to specify the end of a code block that starts with the begin keyword. exception Used to declare an exception type. extern Indicates that a declared program element is defined in another binary or assembly. false Used as a Boolean literal. finally Used together with try to introduce a block of code that executes regardless of whether an exception occurs. for Used in looping constructs. fun Used in lambda expressions, also known as anonymous functions. function Used as a

F# – Modules

F# – Modules ”; Previous Next As per MSDN library, an F# module is a grouping of F# code constructs, such as types, values, function values, and code in do bindings. It is implemented as a common language runtime (CLR) class that has only static members. Depending upon the situation whether the whole file is included in the module, there are two types of module declarations − Top-level module declaration Local module declaration In a top-level module declaration the whole file is included in the module. In this case, the first declaration in the file is the module declaration. You do not have to indent declarations in a top-level module. In a local module declaration, only the declarations that are indented under that module declaration are part of the module. Syntax Syntax for module declaration is as follows − // Top-level module declaration. module [accessibility-modifier] [qualified-namespace.]module-name declarations // Local module declaration. module [accessibility-modifier] module-name = declarations Please note that the accessibility-modifier can be one of the following − public, private, internal. The default is public. The following examples will demonstrate the concepts − Example 1 The module file Arithmetic.fs − module Arithmetic let add x y = x + y let sub x y = x – y let mult x y = x * y let div x y = x / y The program file main.fs − // Fully qualify the function name. open Arithmetic let addRes = Arithmetic.add 25 9 let subRes = Arithmetic.sub 25 9 let multRes = Arithmetic.mult 25 9 let divRes = Arithmetic.div 25 9 printfn “%d” addRes printfn “%d” subRes printfn “%d” multRes printfn “%d” divRes When you compile and execute the program, it yields the following output − 34 16 225 2 110 90 1000 10 Example 2 Live Demo // Module1 module module1 = // Indent all program elements within modules that are declared with an equal sign. let value1 = 100 let module1Function x = x + value1 // Module2 module module2 = let value2 = 200 // Use a qualified name to access the function. // from module1. let module2Function x = x + (module1.module1Function value2) let result = module1.module1Function 25 printfn “%d” result let result2 = module2.module2Function 25 printfn “%d” result2 When you compile and execute the program, it yields the following output − 125 325 Print Page Previous Next Advertisements ”;

F# – Operator Overloading

F# – Operator Overloading ”; Previous Next You can redefine or overload most of the built-in operators available in F#. Thus a programmer can use operators with user-defined types as well. Operators are functions with special names, enclosed in brackets. They must be defined as static class members. Like any other function, an overloaded operator has a return type and a parameter list. The following example, shows a &plus; operator on complex numbers − //overloading &plus; operator static member (&plus;) (a : Complex, b: Complex) = Complex(a.x &plus; b.x, a.y &plus; b.y) The above function implements the addition operator (&plus;) for a user-defined class Complex. It adds the attributes of two objects and returns the resultant Complex object. Implementation of Operator Overloading The following program shows the complete implementation − Live Demo //implementing a complex class with +, and – operators //overloaded type Complex(x: float, y : float) = member this.x = x member this.y = y //overloading + operator static member (+) (a : Complex, b: Complex) = Complex(a.x + b.x, a.y + b.y) //overloading – operator static member (-) (a : Complex, b: Complex) = Complex(a.x – b.x, a.y – b.y) // overriding the ToString method override this.ToString() = this.x.ToString() + ” ” + this.y.ToString() //Creating two complex numbers let c1 = Complex(7.0, 5.0) let c2 = Complex(4.2, 3.1) // addition and subtraction using the //overloaded operators let c3 = c1 + c2 let c4 = c1 – c2 //printing the complex numbers printfn “%s” (c1.ToString()) printfn “%s” (c2.ToString()) printfn “%s” (c3.ToString()) printfn “%s” (c4.ToString()) When you compile and execute the program, it yields the following output − 7 5 4.2 3.1 11.2 8.1 2.8 1.9 Print Page Previous Next Advertisements ”;

F# – Useful Resources

F# – Useful Resources ”; Previous Next The following resources contain additional information on F#. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Javascript Object oriented programming Course – Build Quiz App 61 Lectures 8 hours DigiFisk (Programming Is Fun) More Detail Industry 4.0 – Automation & Applications 35 Lectures 2.5 hours J Aatish Rao More Detail Java Courses in Tamil 188 Lectures 11.5 hours Programming Line More Detail Python for Beginners with Real world applications in Hindi 54 Lectures 8 hours Saurabh Dubey More Detail Data Science and Machine Learning with R from A-Z Course [Updated for 2021] 81 Lectures 28.5 hours Packt Publishing More Detail Internet of Things (IoT) Automation using Raspberry Pi 2 23 Lectures 39 mins Venkatesh Varadachari More Detail Print Page Previous Next Advertisements ”;

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 ”;