F#

0
17

F# – Overwatch

F# is a functional programming language. To understand F# constructs, you need to read a couple of collections abaway correct now presently there the programming paradigm named Functional Programming.

Functional programming treats complaceer programs as maall of thematical functions. In functional programming, the focus would end up being on constants and functions, instead of variables and states. Because functions and constants are slimgs tmind wear don’t alter.

In functional programming, you will write modular programs, i.e., the programs would consist of functions tmind wear will conaspectr other functions as inplace.

Programs written in functional programming language tend to end up being concise.

Abaway correct now presently there F#

Folloearng are the easy information abaway correct now presently there F# −

  • It was produceed in 2005 at Microsmooth Reoceanrch.
  • It is a part of Microsmooth’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 (Microsmooth Intermediate Language) tmind wear runs on CLR (Common Language Runtime).

  • It provides type inference.

  • It provides wealthy pattern go with uping constructs.

  • It has interactionionive scripting and debugging capabilitie ups.

  • It enables writing higher order functions.

  • It provides well produceed object model.

Use of F#

F# is normally used in the folloearng areas −

  • Maruler scientific model
  • Maall of thematical problem solving
  • Artificial intelligence reoceanrch work
  • Financial modelling
  • Graphic style
  • CPU style
  • Compiler programming
  • Telecommunications

It is also used in CRUD apps, web pages, GUI games and other general purpose programs.

F# – Environment Setup

The tools requireddish-coloureddish for F# programming are talk abawayed in this chapter.

Integrated Development Environment(IDE) for F#

Microsmooth provides Visual Studio 2013 for F# programming.

The free Visual Studio 2013 Commdevicey Edition is available from Microsmooth’s awayicial website. Visual Studio 2013 Commdevicey and above comes with the Visual F# Tools. The Visual F# Tools include the command-collection compiler (fsc.exe) and F# Interactionionive (fsi.exe).

Uperform these tools, you can write all kinds of F# programs from easy command-collection applications to more complex applications. You can also write F# source code files uperform a easy text editor, like Notepad, and compile the code into bumembare locateds uperform the command-collection compiler.

You can download it from Microsmooth Visual Studio. It gets automatically instalintroduced in your own machine.

Writing F# Programs On Links

Please visit the F# awayicial website for the latest instructions on getting the tools as a Debian package or compiling all of them immediately from the source − /index.php?s=httpfsharporguselinux.

Try it Option Oncollection

We have set up the F# Programming environment oncollection. You can easily compile and execute all the available examples oncollection alengthy with doing your own theory work. It gives you confidence in wmind wear you are reading and to check the result with various options. Feel free to modify any kind of example and execute it oncollection.

Try the folloearng example uperform the Try it option or use the url − /index.php?s=httpwwwcompileoncollectioncom.

(* This is a comment *)
(* Sample Hello World program uperform F# *)
printfn "Hello World!"

For the majority of of the examples given in this tutorial, you will find a Try it option in our website code sections at the top correct corner tmind wear will conaspectr you to the oncollection compiler. So just make use of it and enjoy your own understanding.

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 exaction same way like any kind of other variable.

In general, an F# application does not have any kind of specific enconsider stage. The compiler executes all top-level statements in the file from top to base.

However, to follow procedural programming style, many kind of applications maintain a performle top level statement tmind wear calls the main loop.

The folloearng code shows a easy F# program −

open System
(* This is a multi-collection comment *)
// This is a performle-collection comment

allow sign num =
   if num > 0 then "positive"
   elif num < 0 then "negative"
   else "zero"

allow main() =
   Console.WriteLine("sign 5: {0}", (sign 5))

main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

sign 5: positive

Please note tmind wear −

  • An F# code file may end up beinggin with a numend up beingr of open statements tmind wear is used to imslot namespaces.

  • The body of the files includes other functions tmind wear implement the business logic of the application.

  • The main loop contains the top executable statements.

F# – Basic Syntax

You have seen the easy structure of an F# program, so it will end up being easy to understand other easy produceing blocks of the F# programming language.

Tokens in F#

An F# program consists of various tokens. A token could end up being a keyword, an identifier, a constant, a string literal, or a symbol. We can categorize F# tokens into 2 types −

  • Keywords
  • Symbol and Operators

F# Keywords

The folloearng table shows the keywords and short descriptions of the keywords. We will talk abaway the use of these keywords in subsequent chapters.

Keyword Description
abstractionion Indicates a method tmind wear either has no implementation in the type in which it is declareddish-coloureddish or tmind wear is virtual and has a default implementation.
and Used in mutually recursive bindings, in real estate declarations, and with multiple constraints on generic parameters.
as Used to give the current course object an object name. Also used to give a name to a whole pattern wislim a pattern go with up.
bumert Used to verify code during debugging.
base Used as the name of the base course object.
end up beinggin In verbose syntax, indicates the start of a code block.
course In verbose syntax, indicates the start of a course definition.
default Indicates an implementation of an abstractionion method; used with each other with an abstractionion method declaration to produce 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 tmind wear 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 memend up beingr definitions.

In verbose syntax, used to specify the end of a code block tmind wear starts with the end up beinggin keyword.

exception Used to declare an exception type.
extern Indicates tmind wear a declareddish-coloureddish program element is defined in an additional binary or bumembly.
false Used as a Boolean literal.
finally Used with each other with consider to introduce a block of code tmind wear 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 shorter alternative to the fun keyword and a go with up expression in a lambda expression tmind wear has pattern go with uping on a performle argument.
global Used to reference the top-level .NET namespace.
if Used in conditional branching constructs.
in Used for sequence expressions and, in verbose syntax, to separate expressions from bindings.
inherit Used to specify a base course or base interface.
incollection Used to indicate a function tmind wear ought to end up being integrated immediately into the caller's code.
interface Used to declare and implement interfaces.
internal Used to specify tmind wear a memend up beingr is noticeable inaspect an bumembly but not away correct now presently thereaspect it.
lazy Used to specify a complaceation tmind wear is to end up being performed only when a result is needed.
allow Used to bumociate, or bind, a name to a value or function.
allow! Used in asynchronous workflows to bind a name to the result of an asynchronous complaceation, or, in other complaceation expressions, used to bind a name to a result, which is of the complaceation type.
go with up Used to branch by comparing a value to a pattern.
memend up beingr Used to declare a real estate or method in an object type.
module Used to bumociate a name with a group of related types, values, and functions, to logically separate it from other code.
mutable Used to declare a variable, tmind wear is, a value tmind wear can end up being alterd.
namespace Used to bumociate a name with a group of related types and modules, to logically separate it from other code.
new

Used to declare, define, or invoke a constructor tmind wear produces or tmind wear can produce an object.

Also used in generic parameter constraints to indicate tmind wear a type must have a specific constructor.

not Not actionionually a keyword. However, not struct in combination is used as a generic parameter constraint.
null

Indicates the absence of an object.

Also used in generic parameter constraints.

of Used in discriminated unions to indicate the type of categories of values, and in delegate and exception declarations.
open Used to make the contents of a namespace or module available withaway correct now presently there qualification.
or

Used with Boolean conditions as a Boolean or operator. Equivalent to ||.

Also used in memend up beingr constraints.

override Used to implement a version of an abstractionion or virtual method tmind wear differs from the base version.
private Rererigorouseds access to a memend up beingr to code in the exaction same type or module.
public Allows access to a memend up beingr from away correct now presently thereaspect the type.
rec Used to indicate tmind wear a function is recursive.
return Used to indicate a value to provide as the result of a complaceation expression.
return! Used to indicate a complaceation expression tmind wear, when evaluated, provides the result of the containing complaceation expression.
select Used in query expressions to specify wmind wear fields or columns to extractionion. Note tmind wear this is a contextual keyword, which means tmind wear it is not actionionually a reserved word and it only actionions like a keyword in appropriate context.
static Used to indicate a method or real estate tmind wear can end up being calintroduced withaway correct now presently there an instance of a type, or a value memend up beingr tmind wear is shareddish-coloureddish among all instances of a type.
struct

Used to declare a structure type.

Also used in generic parameter constraints.

Used for OCaml compatibility in module definitions.

then

Used in conditional expressions.

Also used to perform aspect effects after object construction.

to Used in for loops to indicate a range.
true Used as a Boolean literal.
consider Used to introduce a block of code tmind wear may generate an exception. Used with each other with with or finally.
type Used to declare a course, record, structure, discriminated union, enumeration type, device of measure, or type abbreviation.
upcast Used to convert to a type tmind wear is higher in the inheritance chain.
use Used instead of allow for values tmind wear require Dispose to end up being calintroduced to free resources.
use! Used instead of allow! in asynchronous workflows and other complaceation expressions for values tmind wear require Dispose to end up being calintroduced to free resources.
val Used in a sigcharactioner to indicate a value, or in a type to declare a memend up beingr, in limited situations.
void Indicates the .NET void type. Used when interoperating with other .NET languages.
when Used for Boolean conditions (when guards) on pattern go with upes and to introduce a constraint clause for a generic type parameter.
while Introduces a looping construct.
with Used with each other with the go with up keyword in pattern go with uping expressions. Also used in object expressions, record copying expressions, and type extensions to introduce memend up beingr definitions, and to introduce exception handlers.
yield Used in a sequence expression to produce a value for a sequence.
yield! Used in a complaceation expression to append the result of a given complaceation expression to a collection of results for the containing complaceation expression.

Some reserved keywords came from the OCaml language −

asr land lor lsl lsr lxor mod sig

Some other reserved keywords are kept for future expansion of F#.

atomic break checked component const constraint constructor
continue eager actionionuallyt external fixed functor include
method mixin object parallel process protected pure
oceanintroduced tailcall trait virtual volatile

Comments in F#

F# provides 2 types of comments −

  • One collection comment starts with // symbol.
  • Multi collection comment starts with (* and ends with *).

A Basic Program and Application Enconsider Point in F#

Generally, you don’t have any kind of explicit enconsider stage for F# programs. When you compile an F# application, the final file provided to the compiler end up beingcomes the enconsider stage and all top level statements in tmind wear file are executed from top to base.

A well-written program ought to have a performle top-level statement tmind wear would call the main loop of the program.

A very minimalistic F# program tmind wear would display ‘Hello World’ on the screen −

(* This is a comment *)
(* Sample Hello World program uperform F# *)
printfn "Hello World!"

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hello World!

F# – Data Types

The data types in F# can end up being courseified as follows −

  • Integral types
  • Floating stage types
  • Text types
  • Other types

Integral Data Type

The folloearng table provides the integral data types of F#. These are easyally 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 minimumernern 4 bytes any kind of integer

42I

1499999

9999999

9999999

9999999

9999I

arbitrary precision integer

Example

(* performle byte integer *)
allow x = 268.97f
allow y = 312.58f
allow z = x + y

printfn "x: %f" x
printfn "y: %f" y
printfn "z: %f" z

(* unsigned 8-bit natural numend up beingr *)

allow p = 2uy
allow q = 4uy
allow r = p + q

printfn "p: %i" p
printfn "q: %i" q
printfn "r: %i" r

(* signed 16-bit integer *)

allow a = 12s
allow b = 24s
allow c = a + b

printfn "a: %i" a
printfn "b: %i" b
printfn "c: %i" c

(* signed 32-bit integer *)

allow d = 212l
allow e = 504l
allow 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 folloearng away correct now presently thereplace −

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 folloearng table provides the floating stage 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 stage numend up beingr (7 significan not digit is)
float 8 bytes ±5.0e-324 to ±1.7e308

42.0

-11.0

64-bit signed floating stage numend up beingr (15-16 significan not digit is)
decimal 16 bytes ±1.0e-28 to ±7.9e28

42.0M

-11.0M

128-bit signed floating stage numend up beingr (28-29 significan not digit is)
BigRational At minimumernern 4 bytes Any rational numend up beingr.

42N

-11N

Arbitrary precision rational numend up beingr. Uperform this type requires a reference to FSharp.PowerPack.dll.

Example

(* 32-bit signed floating stage numend up beingr *)
(* 7 significan not digit is *)

allow d = 212.098f
allow e = 504.768f
allow f = d + e

printfn "d: %f" d
printfn "e: %f" e
printfn "f: %f" f

(* 64-bit signed floating stage numend up beingr *)
(* 15-16 significan not digit is *)
allow x = 21290.098
allow y = 50446.768
allow 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 folloearng away correct now presently thereplace −

d: 212.098000
e: 504.768000
f: 716.866000
x: 21290.1
y: 50446.8
z: 71736.9

Text Data Types

The folloearng 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 charactionioners
string 20 + (2 * string's dimension) bytes 0 to abaway correct now presently there 2 billion charactionioners

"Hello"

"World"

Unicode text

Example

allow choice = 'y'
allow name = "Zara Ali"
allow 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 folloearng away correct now presently thereplace −

Choice: y
Name: Zara Ali
Organisation: Tutorials Point

Other Data Types

The folloearng table provides a few other data types of F#.

F# Type Size Range Example Remarks
bool 1 byte Only 2 achievable values, true or false

true

false

Stores boolean values

Example

allow trueVal = true
allow falseVal = false

printfn "True Value: %b" (trueVal)
printfn "False Value: %b" (falseVal)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

True Value: true
False Value: false

F# – Variables

A variable is a name given to a storage area tmind wear our programs can manipulate. Each variable has a specific type, which determines the dimension and layaway correct now presently there of the variable's memory; the range of values tmind wear can end up being storeddish-coloureddish wislim tmind wear memory; and the set of operations tmind wear can end up being appare locatedd to the variable.

Variable Declaration in F#

The allow keyword is used for variable declaration −

For example,

allow x = 10

It declares a variable x and bumigns the value 10 to it.

You can also bumign an expression to a variable −

allow x = 10
allow y = 20
allow z = x + y

The folloearng example illustrates the concept −

Example

allow x = 10
allow y = 20
allow z = x + y

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

x: 10
y: 20
z: 30

Variables in F# are immutable, which means once a variable is bound to a value, it can’t end up being alterd. They are actionionually compiintroduced as static read-only propertie ups.

The folloearng example demonstrates this.

Example

allow x = 10
allow y = 20
allow z = x + y

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

allow x = 15
allow y = 20
allow 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 folloearng error message −

Duplicate definition of value 'x'
Duplicate definition of value 'Y'
Duplicate definition of value 'Z'

Variable Definition With Type Declaration

A variable definition tells the compiler where and how a lot storage for the variable ought to end up being produced. A variable definition may specify a data type and contains a list of one or more variables of tmind wear type as shown in the folloearng example.

Example

allow x:int32 = 10
allow y:int32 = 20
allow z:int32 = x + y

printfn "x: %d" x
printfn "y: %d" y
printfn "z: %d" z

allow p:float = 15.99
allow q:float = 20.78
allow r:float = p + q

printfn "p: %g" p
printfn "q: %g" q
printfn "r: %g" r

When you compile and execute the program, it shows the folloearng error message −

x: 10
y: 20
z: 30
p: 15.99
q: 20.78
r: 36.77

Mutable Variables

At times you need to alter the values storeddish-coloureddish in a variable. To specify tmind wear correct now presently there could end up being a alter in the value of a declareddish-coloureddish and bumigned variable, in later part of a program, F# provides the mutable keyword. You can declare and bumign mutable variables uperform this keyword, in whose values you will alter.

The mutable keyword enables you to declare and bumign values in a mutable variable.

You can bumign a few preliminary value to a mutable variable uperform the allow keyword. However, to bumign new subsequent value to it, you need to use the operator.

For example,

allow mutable x = 10
x ← 15

The folloearng example will clear the concept −

Example

allow mutable x = 10
allow y = 20
allow mutable z = x + y

printfn "Original Values:"
printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

printfn "Let us alter the value of x"
printfn "Value of z will alter 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 folloearng away correct now presently thereplace −

Original Values:
x: 10
y: 20
z: 30
Let us alter the value of x
Value of z will alter too.
New Values:
x: 15
y: 20
z: 35

F# – Operators

An operator is a symbol tmind wear tells the compiler to perform specific maall of thematical or logical manipulations. F# is wealthy in built-in operators and provides the folloearng types of operators −

  • Arithmetic Operators
  • Comparison Operators
  • Boolean Operators
  • Bitwise Operators

Arithmetic Operators

The folloearng table shows all the arithmetic operators supsloted by F# language. Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
+ Adds 2 operands A + B will give 30
Subtractionions second operand from the preliminary A – B will give -10
* Multipare locateds 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 an additional B**A will give 2010

Example

allow a : int32 = 21
allow b : int32 = 10

allow mutable c = a + b
printfn "Line 1 - Value of c is %d" c

c <- a - b;
printfn "Line 2 - Value of c is %d" c

c <- a * b;
printfn "Line 3 - Value of c is %d" c

c <- a / b;
printfn "Line 4 - Value of c is %d" c

c <- a % b;
printfn "Line 5 - Value of c is %d" c

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1

Comparison Operators

The folloearng table shows all the comparison operators supsloted by F# language. These binary comparison operators are available for integral and floating-stage types. These operators return values of type bool.

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example
= Checks if the values of 2 operands are equal or not, if yes then condition end up beingcomes true. (A == B) is not true.
<> Checks if the values of 2 operands are equal or not, if values are not equal then condition end up beingcomes true. (A <> B) is true.
> Checks if the value of left operand is greater than the value of correct operand, if yes then condition end up beingcomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of correct operand, if yes then condition end up beingcomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of correct operand, if yes then condition end up beingcomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of correct operand, if yes then condition end up beingcomes true. (A <= B) is true.

Example

allow mutable a : int32 = 21
allow mutable b : int32 = 10

if (a = b) then
   printfn "Line 1 - a is equal to b"
else
   printfn "Line 1 - a is not equal to b"

if (a < b) then
   printfn "Line 2 - a is less than b"
else
   printfn "Line 2 - a is not less than b"

if (a > b) then
   printfn "Line 3 - a is greater than b"
else
   printfn "Line 3 - a is not greater than b"

(* Lets alter value of a and b *)
a <- 5
b <- 20

if (a <= b) then
   printfn "Line 4 - a is either less than or equal to b"
else
   printfn "Line4 - a is a is greater than b"

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b

Boolean Operators

The folloearng table shows all the Boolean operators supsloted by F# language. Assume variable A holds true and variable B holds false, then −

Operator Description Example
&& Calintroduced Boolean AND operator. If both the operands are non-zero, then condition end up beingcomes true. (A && B) is false.
|| Calintroduced Boolean OR Operator. If any kind of of the 2 operands is non-zero, then condition end up beingcomes true. (A || B) is true.
not Calintroduced Boolean NOT Operator. Use to reverses the logical state of it is operand. If a condition is true then Logical NOT operator will make false. not (A && B) is true.

Example

allow mutable a : bool = true;
allow mutable b : bool = true;

if ( a && b ) then
   printfn "Line 1 - Condition is true"
else
   printfn "Line 1 - Condition is not true"

if ( a || b ) then
   printfn "Line 2 - Condition is true"
else
   printfn "Line 2 - Condition is not true"

(* allows alter the value of a *)

a <- false
if ( a && b ) then
   printfn "Line 3 - Condition is true"
else
   printfn "Line 3 - Condition is not true"

if ( a || b ) then
   printfn "Line 4 - Condition is true"
else
   printfn "Line 4 - Condition is not true"

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators

Bitwise operators work on bit is and perform bit-by-bit operation. The truth tables for &&& (bitwise AND), ||| (bitwise OR), and ^^^ (bitwise exclusive OR) are as follows −

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 end up being 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 supsloted by F# language are listed in the folloearng table. Assume variable A holds 60 and variable B holds 13, then −

Operator Description Example
&&& Binary AND Operator copies a lttle bit to the result if it exists in both operands. (A &&& B) will give 12, which is 0000 1100
||| Binary OR Operator copies a lttle 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' bit is. (~~~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 numend up beingr of bit is specified by the correct operand. A <<< 2 will give 240 which is 1111 0000
>>> Binary Right Shift Operator. The left operands value is moved correct by the numend up beingr of bit is specified by the correct operand. A >>> 2 will give 15 which is 0000 1111

Example

allow a : int32 = 60 // 60 = 0011 1100
allow b : int32 = 13 // 13 = 0000 1101
allow mutable c : int32 = 0

c <- a &&& b // 12 = 0000 1100
printfn "Line 1 - Value of c is %d" c

c <- a ||| b // 61 = 0011 1101
printfn "Line 2 - Value of c is %d" c

c <- a ^^^ b // 49 = 0011 0001
printfn "Line 3 - Value of c is %d" c

c = ~~~a // -61 = 1100 0011
printfn "Line 4 - Value of c is %d" c

c <- a <<< 2 // 240 = 1111 0000
printfn "Line 5 - Value of c is %d" c

c <- a >>> 2 // 15 = 0000 1111
printfn "Line 6 - Value of c is %d" c

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is 49
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Operators Precedence

The folloearng table shows the order of precedence of operators and other expression keywords in the F# language, from lowest precedence to the highest precedence.

Operator Associativity
as Right
when Right
| (pipe) Left
; Right
allow Non bumociative
function, fun, go with up, consider Non bumociative
if Non bumociative
Right
:= Right
, Non bumociative
or, || Left
&, && Left
< op, >op, =, |op, &op Left
&&& , |||, ^^^, ~~~, <<<, >>> Left
^ op Right
:: Right
:?>, 😕 Non bumociative
– op, +op, (binary) Left
* op, /op, %op Left
** op Right
f x (function application) Left
| (pattern go with up) Right
prefix operators (+op, -op, %, %%, &, &&, !op, ~op) Left
. Left
f(x) Left
f<types> Left

Example

allow a : int32 = 20
allow b : int32 = 10
allow c : int32 = 15
allow d : int32 = 5

allow mutable e : int32 = 0
e <- (a + b) * c / d // ( 30 * 15 ) / 5
printfn "Value of (a + b) * c / d is : %d" e

e <- ((a + b) * c) / d // (30 * 15 ) / 5
printfn "Value of ((a + b) * c) / d is : %d" e

e <- (a + b) * (c / d) // (30) * (15/5)
printfn "Value of (a + b) * (c / d) is : %d" e

e <- a + (b * c) / d // 20 + (150/5)
printfn "Value of a + (b * c) / d is : %d" e

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Value of (a + b) * c / d is : 90 
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90 
Value of a + (b * c) / d is : 50

F# – Decision Maruler

Decision maruler structures require tmind wear the programmer specify one or more conditions to end up being evaluated or tested by the program. It ought to end up being alengthy with a statement or statements to end up being executed if the condition is determined to end up being true, and optionally, other statements to end up being executed if the condition is determined to end up being false.

Folloearng is the general form of a typical decision maruler structure found in the majority of of the programming languages −

Decision Maruler

F# programming language provides the folloearng types of decision maruler statements.

Statement Description
if /then statement An if/then statement consists of a Boolean expression followed by one or more statements.
if/then/ else statement An if/then statement can end up being followed by an optional else statement, which executes when the Boolean expression is false.
if/then/elif/else statement An if/then/elif/else statement enables you to have multiple else branches.
nested if statements You can use one if or else if statement inaspect an additional if or else if statement(s).

F#-if/then Statement

An if/then statement consists of a Boolean expression followed by one or more statements.

Syntax

The if/then construct in F# has the folloearng syntax −

(* easy if *)
if expr then
   expr

Flow diagram

If then Statement

Example

allow a : int32 = 10

(* check the boolean condition uperform if statement *)
if (a < 20) then
   printfn "a is less than 20n"
   printfn "Value of a is: %d" a

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

a is less than 20

Value of a is: 10

F#-if/then/else Statement

An if/then statement can end up being followed by an optional else statement, which executes when the Boolean expression is false.

Syntax

The syntax of an if/then/else statement in F# programming language is −

if expr then
   expr
else
   expr

Flow Diagram

Else Statement

Example

allow a : int32 = 100

(* check the boolean condition uperform if statement *)

if (a < 20) then
   printfn "a is less than 20n"
else
   printfn "a is not less than 20n"
   printfn "Value of a is: %d" a

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

a is not less than 20

Value of a is: 100

F#-if/then/elif/else Statement

An if/then/elif/else construct has multiple else branches.

Syntax

The syntax of an if/then/elif/else statement in F# programming language is −

if expr then
   expr
elif expr then
   expr
elif expr then
   expr
...
else
   expr

Example

allow a : int32 = 100

(* check the boolean condition uperform if statement *)

if (a = 10) then
   printfn "Value of a is 10n"
elif (a = 20) then
   printfn " Value of a is 20n"
elif (a = 30) then
   printfn " Value of a is 30n"
else
   printfn " None of the values are go with upingn"
   printfn "Value of a is: %d" a

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

None of the values are go with uping

Value of a is: 100

F#-Nested if Statements

It is always legal in F# programming to nest if/then or if/then/else statements, which means you can use one if or else if statement inaspect an additional if or else if statement(s).

Syntax

if expr then
   expr
   if expr then
      expr
   else
      expr
else
   expr

Example

allow a : int32 = 100
allow b : int32 = 200

(* check the boolean condition uperform if statement *)

if (a = 100) then
(* if condition is true then check the folloearng *)

   if (b = 200) then
      printfn "Value of a is 100 and b is 200n"
printfn "Exactionion value of a is: %d" a
printfn "Exactionion value of b is: %d" b

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Value of a is 100 and b is 200

Exactionion value of a is: 100
Exactionion value of b is: 200

F# – Loops

Programming languages provide various manage structures tmind wear enable for more complicated execution paths.

A loop statement enables us to execute a statement or group of statements multiple times and folloearng is the general form of a loop statement in the majority of of the programming languages −

Loop Statement

F# provides the folloearng types of loops to handle the looping requirements.

Loop Type Description
for… to and for… downto expressions The for…to expression is used to iterate in a loop over a range of values of a loop variable. The for… downto expression reddish-coloureddishuces the value of loop variable.
for … in expression This form of for loop is used to iterate over collections of items i.e., loops over collections and sequences
While…do loop Repeats a statement or group of statements while a given condition is true. It tests the condition end up beingfore executing the loop body.
nested loops You can use one or more loop inaspect any kind of other for or while loop.

F#-for…to and for…downto Expressions

A for loop is a repetition manage structure tmind wear enables you to effectively write a loop tmind wear needs to execute a specific numend up beingr of times.

Syntax

The syntax of a for…to loop in F# programming language is −

for var = start-expr to end-expr do
   ... // loop body

The syntax of a for…downto loop in F# programming language is −

for var = start-expr downto end-expr do
   ... // loop body

Example 1

The folloearng program prints away correct now presently there the numend up beingrs 1 – 20 −

allow main() =
   for i = 1 to 20 do
      printfn "i: %i" i
main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10
i: 11
i: 12
i: 13
i: 14
i: 15
i: 16
i: 17
i: 18
i: 19
i: 20

Example 2

The folloearng program counts in reverse and prints away correct now presently there the numend up beingrs 20 – 1 −

allow main() =
   for i = 20 downto 1 do
      printfn "i: %i" i
main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

i: 20
i: 19
i: 18
i: 17
i: 16
i: 15
i: 14
i: 13
i: 12
i: 11
i: 10
i: 9
i: 8
i: 7
i: 6
i: 5
i: 4
i: 3
i: 2
i: 1

F#-for…in Expressions

This looping construct is used to iterate over the go with upes of a pattern in an enumerable collection such as a range expression, sequence, list, array, or other construct tmind wear supslots enumeration.

Syntax

for pattern in enumerable-expression do
   body-expression

Example

The folloearng program illustrates the concept −

// Looping over a list.
allow list1 = [ 10; 25; 34; 45; 78 ]
for i in list1 do
   printfn "%d" i

// Looping over a sequence.
allow seq1 = seq { for i in 1 .. 10 -> (i, i*i) }
for (a, asqr) in seq1 do
   printfn "%d squareddish-coloureddish is %d" a asqr

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

10
25
34
45
78
1 squareddish-coloureddish is 1
2 squareddish-coloureddish is 4
3 squareddish-coloureddish is 9
4 squareddish-coloureddish is 16
5 squareddish-coloureddish is 25
6 squareddish-coloureddish is 36
7 squareddish-coloureddish is 49
8 squareddish-coloureddish is 64
9 squareddish-coloureddish is 81
10 squareddish-coloureddish is 100

F#-While…do Expressions

The while…do expression is used to perform iterative execution while a specified test condition is true.

Syntax

while test-expression do
   body-expression

The test-expression is evaluated preliminary; if it is true, the body-expression is executed and the test expression is evaluated again. The body-expression must have type device, i.e., it ought to not return any kind of value. If the test expression is false, the iteration ends.

Example

allow mutable a = 10
while (a < 20) do
   printfn "value of a: %d" a
   a <- a + 1

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

F#-Nested Loops

F# programming language enables to use one loop inaspect an additional loop.

Syntax

The syntax for a nested for loop statement could end up being as follows −

for var1 = start-expr1 to end-expr1 do
   for var2 = start-expr2 to end-expr2 do
      ... // loop body

The syntax for a nested while loop statement could end up being as follows −

while test-expression1 do
   while test-expression2 do
      body-expression

Example

allow main() =
   for i = 1 to 5 do
      printf "n"
      for j = 1 to 3 do
         printf "*"
main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

***
***
***
***
***

F# – Functions

In F#, functions work like data types. You can declare and use a function in the exaction same way like any kind of other variable.

Since functions can end up being used like any kind of other variables, you can −

  • Create a function, with a name and bumociate tmind wear name with a type.
  • Assign it a value.
  • Perform a few calculation on tmind wear value.
  • Pbum it as a parameter to an additional function or sub-raway correct now presently thereine.
  • Return a function as the result of an additional function.

Defining a Function

Functions are defined by uperform the allow keyword. A function definition has the folloearng syntax −

allow [incollection] function-name parameter-list [ : return-type ]
= function-body

Where,

  • function-name is an identifier tmind wear represents the function.

  • parameter-list gives the list of parameters separated by spaces. You can also specify an explicit type for each parameter and if not specified compiler tends to deduce it from the function body (like variables).

  • function-body consists of an expression, or a compound expression consisting of a numend up beingr of expressions. The final expression in the function body is the return value.

  • return-type is a colon followed by a type and is optional. If the return type is not specified, then the compiler determines it from the final expression in the function body.

Parameters of a Function

You list the names of parameters correct after the function name. You can specify the type of a parameter. The type of the parameter ought to follow the name of the parameter separated by a colon.

If no parameter type is specified, it is inferreddish-coloureddish by the compiler.

For example −

allow doubleIt (x : int) = 2 * x

Calling a Function

A function is calintroduced by specifying the function name followed by a space and then any kind of arguments separated by spaces.

For example −

allow vol = cylinderVolume 3.0 5.0

The folloearng programs illustrate the concepts.

Example 1

The folloearng program calculates the volume of a cylinder when the radius and dimension are given as parameters.

// the function calculates the volume of
// a cylinder with radius and dimension as parameters

allow cylinderVolume radius dimension : float =

   // function body
   allow pi = 3.14159
   dimension * pi * radius * radius

allow vol = cylinderVolume 3.0 5.0
printfn " Volume: %g " vol

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Volume: 141.372

Example 2

The folloearng program returns the huger value of 2 given parameters −

// the function returns the huger value end up beingtween 2
// arguments

allow max num1 num2 : int32 =
   // function body
   if(num1>num2)then
      num1
   else
      num2

allow res = max 39 52
printfn " Max Value: %d " res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Max Value: 52

Example 3

allow doubleIt (x : int) = 2 * x
printfn "Double 19: %d" ( doubleIt(19))

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Double 19: 38

Recursive Functions

Recursive functions are functions tmind wear call all of themselves.

You define a recursive uperform the allow rec keyword combination.

Syntax for defining a recursive function is −

//Recursive function definition
allow rec function-name parameter-list = recursive-function-body

For example −

allow rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)

Example 1

The folloearng program returns Fibonacci 1 to 10 −

allow rec fib n = if n < 2 then 1 else fib (n - 1) + fib (n - 2)
for i = 1 to 10 do
   printfn "Fibonacci %d: %d" i (fib i)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Fibonacci 1: 1
Fibonacci 2: 2
Fibonacci 3: 3
Fibonacci 4: 5
Fibonacci 5: 8
Fibonacci 6: 13
Fibonacci 7: 21
Fibonacci 8: 34
Fibonacci 9: 55
Fibonacci 10: 89

Example 2

The folloearng program returns realityionorial 8 −

open System
allow rec realityion x =
   if x < 1 then 1
   else x * realityion (x - 1)
Console.WriteLine(realityion 8)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

40320

Arrow Notations in F#

F# reslots abaway correct now presently there data type in functions and values, uperform a chained arrow notation. Let us conaspectr an example of a function tmind wear conaspectrs one int inplace, and returns a string. In arrow notation, it is written as −

int -> string

Data types are read from left to correct.

Let us conaspectr an additional hypothetical function tmind wear conaspectrs 2 int data inplaces and returns a string.

allow mydivfunction x y = (x / y).ToString();;

F# reslots the data type uperform chained arrow notation as −

val mydivfunction : x:int -> y:int -> string

The return type is represented by the correctthe majority of data type in chained arrow notation.

Some more examples −

Notation Meaning
float → float → float The function conaspectrs 2 float inplaces, returns an additional float.
int → string → float The function conaspectrs an int and a string inplace, returns a float.

Lambda Expressions

A lambda expression is an unnamed function.

Let us conaspectr an example of 2 functions −

allow applyFunction ( f: int -> int -> int) x y = f x y
allow mul x y = x * y
allow res = applyFunction mul 5 7
printfn "%d" res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

35

Now in the above example, if instead of defining the function mul, we could have used lambda expressions as −

allow applyFunction ( f: int -> int -> int) x y = f x y
allow res = applyFunction (fun x y -> x * y ) 5 7
printfn "%d" res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

35

Function Composition and Pipelining

In F#, one function can end up being composed from other functions.

The folloearng example shows the composition of a function named f, from 2 functions function1 and function2 −

allow function1 x = x + 1
allow function2 x = x * 5

allow f = function1 >> function2
allow res = f 10
printfn "%d" res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

55

F# also provides a feature calintroduced pipelining of functions. Pipelining enables function calls to end up being chained with each other as successive operations.

The folloearng example shows tmind wear −

allow function1 x = x + 1
allow function2 x = x * 5

allow res = 10 |> function1 |> function2
printfn "%d" res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

55

F# – Strings

In F#, the string type represents immutable text as a sequence of Unicode charactionioners.

String Literals

String literals are delimited by the quotation mark (") charactionioner.

Some special charactionioners are correct now presently there for special uses like newcollection, tab, etc. They are encoded uperform backslash () charactionioner. The backslash charactionioner and the related charactionioner make the escape sequence. The folloearng table shows the escape sequence supsloted by F#.

Charactionioner Escape sequence
Backspace b
Newcollection n
Carriage return r
Tab t
Backslash \
Quotation mark "
Apostrophe '
Unicode charactionioner uXXXX or UXXXXXXXX (where X indicates a hexadecimal digit)

Ways of lgnoring the Escape Sequence

The folloearng 2 ways makes the compiler ignore the escape sequence −

  • Uperform the @ symbol.
  • Encloperform the string in triple quotes.

When a string literal is preceded by the @ symbol, it is calintroduced a verbatim string. In tmind wear way, all escape sequences in the string are ignoreddish-coloureddish, except tmind wear 2 quotation mark charactionioners are interpreted as one quotation mark charactionioner.

When a string is enshutd by triple quotes, then also all escape sequences are ignoreddish-coloureddish, including double quotation mark charactionioners.

Example

The folloearng example demonstrates this technique footweararng how to work with XML or other structures tmind wear include emend up beingdded quotation marks −

// Uperform a verbatim string
allow xmldata = @"<book author=""Lewis, C.S"" title=""Narnia"">"
printfn "%s" xmldata

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

<book author="Lewis, C.S" title="Narnia">

Basic Operators on Strings

The folloearng table shows the easy operations on strings −

Value Description
collect : (char → string) → string → string Creates a new string in whose charactionioners are the results of applying a specified function to each of the charactionioners of the inplace string and concatenating the resulting strings.
concat : string → seq<string> → string Returns a new string made by concatenating the given strings with a separator.
exists : (char → bool) → string → bool Tests if any kind of charactionioner of the string satisfies the given preddish-coloureddishicate.
forall : (char → bool) → string → bool Tests if all charactionioners in the string satisfy the given preddish-coloureddishicate.
init : int → (int → string) → string Creates a new string in whose charactionioners are the results of applying a specified function to each index and concatenating the resulting strings.
iter : (char → device) → string → device Appare locateds a specified function to each charactionioner in the string.
iteri : (int → char → device) → string → device Appare locateds a specified function to the index of each charactionioner in the string and the charactionioner it iself.
dimension : string → int Returns the dimension of the string.
chart : (char → char) → string → string Creates a new string in whose charactionioners are the results of applying a specified function to each of the charactionioners of the inplace string.
charti : (int → char → char) → string → string Creates a new string in whose charactionioners are the results of applying a specified function to each charactionioner and index of the inplace string.
replicate : int → string → string Returns a string by concatenating a specified numend up beingr of instances of a string.

The folloearng examples demonstrate the uses of a few of the above functionalitie ups −

Example 1

The String.collect function produces a new string in whose charactionioners are the results of applying a specified function to each of the charactionioners of the inplace string and concatenating the resulting strings.

allow collectTesting inplaceS =
   String.collect (fun c -> sprintf "%c " c) inplaceS
printfn "%s" (collectTesting "Happy New Year!")

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

H a p p y N e w Y e a r !

Example 2

The String.concat function concatenates a given sequence of strings with a separator and returns a new string.

allow strings = [ "Tutorials Point"; "Coding Ground"; "Absolute Clbumes" ]
allow ourProducts = String.concat "n" strings
printfn "%s" ourProducts

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Tutorials Point
Coding Ground
Absolute Clbumes

Example 3

The String.replicate method returns a string by concatenating a specified numend up beingr of instances of a string.

printfn "%s" <| String.replicate 10 "*! "

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

*! *! *! *! *! *! *! *! *! *!

F# – Options

The option type in F# is used in calculations when correct now presently there may or may not exist a value for a variable or function. Option types are used for representing optional values in calculations. They can have 2 achievable values − Some(x) or None.

For example, a function performing a division will return a value in normal situation, but will throw exceptions in case of a zero denominator. Uperform options here will help to indicate whether the function has succeeded or faiintroduced.

An option has an underlying type and can hold a value of tmind wear type, or it may not have a value.

Uperform Options

Let us conaspectr the example of division function. The folloearng program exfundamentals this −

Let us write a function div, and send 2 arguments to it 20 and 5 −

allow div x y = x / y
allow res = div 20 5
printfn "Result: %d" res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Result: 4

If the second argument is zero, then the program throws an exception −

allow div x y = x / y
allow res = div 20 0
printfn "Result: %d" res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Unhandintroduced Exception:
System.DivideByZeroException: Division by zero

In such cases, we can use option types to return Some (value) when the operation is successful or None if the operation fails.

The folloearng example demonstrates the use of options −

Example

allow div x y =
   go with up y with
   | 0 -> None
   | _ -> Some(x/y)

allow res : int option = div 20 4
printfn "Result: %A " res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Result: Some 5

Option Propertie ups and Methods

The option type supslots the folloearng propertie ups and methods −

Property or method Type Description
None 'T option A static real estate tmind wear enables you to produce an option value tmind wear has the None value.
IsNone bool Returns true if the option has the None value.
IsSome bool Returns true if the option has a value tmind wear is not None.
Some 'T option A static memend up beingr tmind wear produces an option tmind wear has a value tmind wear is not None.
Value 'T Returns the underlying value, or throws a NullReferenceException if the value is None.

Example 1

allow checkPositive (a : int) =
   if a > 0 then
      Some(a)
   else
      None

allow res : int option = checkPositive(-31)
printfn "Result: %A " res

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Result: <null>

Example 2

allow div x y =
   go with up y with
   | 0 -> None
   | _ -> Some(x/y)

allow res : int option = div 20 4
printfn "Result: %A " res
printfn "Result: %A " res.Value

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Result: Some 5
Result: 5

Example 3

allow isHundreddish-coloureddish = function
   | Some(100) -> true
   | Some(_) | None -> false

printfn "%A" (isHundreddish-coloureddish (Some(45)))
printfn "%A" (isHundreddish-coloureddish (Some(100)))
printfn "%A" (isHundreddish-coloureddish None)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

false
true
false

F# – Tuples

A tuple is a comma-separated collection of values. These are used for creating ad hoc data structures, which group with each other related values.

For example, (“Zara Ali”, “Hyderabad”, 10) is a 3-tuple with 2 string values and an int value, it has the type (string * string * int).

Tuples could end up being pairs, triples, and so on, of the exaction same or various types.

Some examples are provided here −

// Tuple of 2 integers.
( 4, 5 )

// Triple of strings.
( "one", "2", "three" )

// Tuple of unknown types.
( a, b )

// Tuple tmind wear has mixed types.
( "Absolute Clbumes", 1, 2.0 )

// Tuple of integer expressions.
( a * 4, b + 7)

Example

This program has a function tmind wear conaspectrs a tuple of four float values and returns the average −

allow averageFour (a, b, c, d) =
   allow sum = a + b + c + d
   sum / 4.0

allow avg:float = averageFour (4.0, 5.1, 8.0, 12.0)
printfn "Avg of four numend up beingrs: %f" avg

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Avg of four numend up beingrs: 7.275000

Accesperform Individual Tuple Memend up beingrs

The individual memend up beingrs of a tuple could end up being bumessed and printed uperform pattern go with uping.

The folloearng example illustrates the concept −

Example

allow display tuple1 =
   go with up tuple1 with
   | (a, b, c) -> printfn "Detail Info: %A %A %A" a b c

display ("Zara Ali", "Hyderabad", 10 )

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Detail Info: "Zara Ali" "Hyderabad" 10

F# has 2 built-in functions, fst and snd, which return the preliminary and second items in a 2-tuple.

The folloearng example illustrates the concept −

Example

printfn "First memend up beingr: %A" (fst(23, 30))
printfn "Second memend up beingr: %A" (snd(23, 30))

printfn "First memend up beingr: %A" (fst("Hello", "World!"))
printfn "Second memend up beingr: %A" (snd("Hello", "World!"))

allow nameTuple = ("Zara", "Ali")

printfn "First Name: %A" (fst nameTuple)
printfn "Second Name: %A" (snd nameTuple)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

First memend up beingr: 23
Second memend up beingr: 30
First memend up beingr: "Hello"
Second memend up beingr: "World!"
First Name: "Zara"
Second Name: "Ali"

F# – Records

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 uperform 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 produce a record by specifying the record's fields. For example, allow us produce a website record named homepage

allow homepage = { Title = "TutorialsPoint"; Url = "www.tutorialsstage.com" }

The folloearng examples will exfundamental the concepts −

Example 1

This program defines a record type named website. Then it produces a few records of type website and prints the records.

(* defining a record type named website *)
type website =
   { Title : string;
      Url : string }

(* creating a few records *)
allow homepage = { Title = "TutorialsPoint"; Url = "www.tutorialsstage.com" }
allow cpage = { Title = "Learn C"; Url = "www.tutorialsstage.com/cprogramming/index.htm" }
allow fsharppage = { Title = "Learn F#"; Url = "www.tutorialsstage.com/fsharp/index.htm" }
allow csharppage = { Title = "Learn C#"; Url = "www.tutorialsstage.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 folloearng away correct now presently thereplace −

Home Page: Title: "TutorialsPoint"
       URL: "www.tutorialsstage.com"
C Page: Title: "Learn C"
      URL: "www.tutorialsstage.com/cprogramming/index.htm"
F# Page: Title: "Learn F#"
      URL: "www.tutorialsstage.com/fsharp/index.htm"
C# Page: Title: "Learn C#"
      URL: "www.tutorialsstage.com/csharp/index.htm"

Example 2

type college student =
   { Name : string;
      ID : int;
      RegistrationText : string;
      IsRegistereddish-coloureddish : bool }

allow getStudent name id =
   { Name = name; ID = id; RegistrationText = null; IsRegistereddish-coloureddish = false }

allow registerStudent st =
   { st with
      RegistrationText = "Registereddish-coloureddish";
      IsRegistereddish-coloureddish = true }

allow printStudent msg st =
   printfn "%s: %A" msg st

allow main() =
   allow preRegistereddish-coloureddishStudent = getStudent "Zara" 10
   allow postRegistereddish-coloureddishStudent = registerStudent preRegistereddish-coloureddishStudent

   printStudent "Before Registration: " preRegistereddish-coloureddishStudent
   printStudent "After Registration: " postRegistereddish-coloureddishStudent

main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Before Registration: : {Name = "Zara";
   ID = 10;
   RegistrationText = null;
   IsRegistereddish-coloureddish = false;}
After Registration: : {Name = "Zara";
   ID = 10;
   RegistrationText = "Registereddish-coloureddish";
   IsRegistereddish-coloureddish = true;}

F# – Lists

In F#, a list is an ordereddish-coloureddish, immutable series of elements of the exaction same type. It is to a few extent equivalent to a linked list data structure.

The F# module, Microsmooth.FSharp.Collections.List, has the common operations on lists. However F# imslots this module automatically and makes it accessible to every F# application.

Creating and Initializing a List

Folloearng are the various ways of creating lists −

  • Uperform list literals.

  • Uperform cons (::) operator.

  • Uperform the List.init method of List module.

  • Uperform a few syntactionionic constructs calintroduced List Comprehensions.

List Literals

In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example:

allow list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

The cons (::) Operator

With this method, you can add a few values by prepending or cons-ing it to an existing list uperform the :: operator. For example −

allow list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

[] denotes an empty list.

List init Method

The List.init method of the List module is often used for creating lists. This method has the type −

val init : int -> (int -> 'T) -> 'T list

The preliminary argument is the desireddish-coloureddish dimension of the new list, and the second argument is an preliminaryizer function, which generates items in the list.

For example,

allow list5 = List.init 5 (fun index -> (index, index * index, index * index * index))

Here, the index function generates the list.

List Comprehensions

List comprehensions are special syntactionionic constructs used for generating lists.

F# list comprehension syntax comes in 2 forms − ranges and generators.

Ranges have the constructs − [start .. end] and [start .. step .. end]

For example,

allow list3 = [1 .. 10]

Generators have the construct − [for x in collection do … yield expr]

For example,

allow list6 = [ for a in 1 .. 10 do yield (a * a) ]

As the yield keyword pushes a performle value into a list, the keyword, yield!, pushes a collection of values into the list.

The folloearng function demonstrates the above methods −

Example

(* uperform list literals *)
allow list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
printfn "The list: %A" list1

(*uperform cons operator *)
allow list2 = 1 :: 2 :: 3 :: []
printfn "The list: %A" list2

(* uperform range constructs*)
allow list3 = [1 .. 10]
printfn "The list: %A" list3

(* uperform range constructs *)
allow list4 = ['a' .. 'm']
printfn "The list: %A" list4

(* uperform init method *)
allow list5 = List.init 5 (fun index -> (index, index * index, index * index * index))
printfn "The list: %A" list5

(* uperform yield operator *)
allow list6 = [ for a in 1 .. 10 do yield (a * a) ]
printfn "The list: %A" list6

(* uperform yield operator *)
allow list7 = [ for a in 1 .. 100 do if a % 3 = 0 && a % 5 = 0 then yield a]
printfn "The list: %A" list7

(* uperform yield! operator *)
allow list8 = [for a in 1 .. 3 do yield! [ a .. a + 3 ] ]
printfn "The list: %A" list8

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
The list: [1; 2; 3]
The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
The list: ['a'; 'b'; 'c'; 'd'; 'e'; 'f'; 'g'; 'h'; 'i'; 'j'; 'k'; 'l'; 'm']
The list: [(0, 0, 0); (1, 1, 1); (2, 4, 8); (3, 9, 27); (4, 16, 64)]
The list: [1; 4; 9; 16; 25; 36; 49; 64; 81; 100]
The list: [15; 30; 45; 60; 75; 90]
The list: [1; 2; 3; 4; 2; 3; 4; 5; 3; 4; 5; 6]

Propertie ups of List Data Type

The folloearng table shows various propertie ups of list data type −

Property Type Description
Head 'T The preliminary element.
Empty 'T list A static real estate tmind wear returns an empty list of the appropriate type.
IsEmpty bool true if the list has no elements.
Item 'T The element at the specified index (zero-based).
Length int The numend up beingr of elements.
Tail 'T list The list withaway correct now presently there the preliminary element.

The folloearng example shows the use of these propertie ups −

Example

allow list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ]

// Use of Propertie ups
printfn "list1.IsEmpty is %b" (list1.IsEmpty)
printfn "list1.Length is %d" (list1.Length)
printfn "list1.Head is %d" (list1.Head)
printfn "list1.Tail.Head is %d" (list1.Tail.Head)
printfn "list1.Tail.Tail.Head is %d" (list1.Tail.Tail.Head)
printfn "list1.Item(1) is %d" (list1.Item(1))

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

list1.IsEmpty is false
list1.Length is 8
list1.Head is 2
list1.Tail.Head is 4
list1.Tail.Tail.Head is 6
list1.Item(1) is 4

Basic Operators on List

The folloearng table shows the easy operations on list data type −

Value Description
append : 'T list → 'T list → 'T list Returns a new list tmind wear contains the elements of the preliminary list followed by elements of the second.
average : 'T list → ^T Returns the average of the elements in the list.
averageBy : ('T → ^U) → 'T list → ^U Returns the average of the elements generated by applying the function to each element of the list.
choose : ('T → 'U option) → 'T list → 'U list Appare locateds the given function to each element of the list. Returns the list comprised of the results for each element where the function returns Some.
collect : ('T → 'U list) → 'T list → 'U list For each element of the list, appare locateds the given function. Concatenates all the results and return the combined list.
concat : seq<'T list> → 'T list Returns a new list tmind wear contains the elements of each the lists in order.
empty : 'T list Returns an empty list of the given type.
exists : ('T → bool) → 'T list → bool Tests if any kind of element of the list satisfies the given preddish-coloureddishicate.
exists2 : ('T1 → 'T2 → bool) → 'T1 list → 'T2 list → bool Tests if any kind of pair of corresponding elements of the lists satisfies the given preddish-coloureddishicate.
filter : ('T → bool) → 'T list → 'T list Returns a new collection containing only the elements of the collection for which the given preddish-coloureddishicate returns true.
find : ('T → bool) → 'T list → 'T Returns the preliminary element for which the given function returns true.
findIndex : ('T → bool) → 'T list → int Returns the index of the preliminary element in the list tmind wear satisfies the given preddish-coloureddishicate.
fold : ('State → 'T → 'State) → 'State → 'T list → 'State Appare locateds a function to each element of the collection, threading an accumulator argument through the complaceation. This function conaspectrs the second argument, and appare locateds the function to it and the preliminary element of the list. Then, it movees this result into the function alengthy with the second element, and so on. Finally, it returns the final result. If the inplace function is f and the elements are i0…iN, then this function complacees f (… (f s i0) i1 …) iN.
fold2 : ('State → 'T1 → 'T2 → 'State) → 'State → 'T1 list → 'T2 list → 'State Appare locateds a function to corresponding elements of 2 collections, threading an accumulator argument through the complaceation. The collections must have identical dimensions. If the inplace function is f and the elements are i0…iN and j0…jN, then this function complacees f (… (f s i0 j0)…) iN jN.
foldBack : ('T → 'State → 'State) → 'T list → 'State → 'State Appare locateds a function to each element of the collection, threading an accumulator argument through the complaceation. If the inplace function isf and the elements are i0…iN then complacees f i0 (…(f iN s)).
foldBack2 : ('T1 → 'T2 → 'State → 'State) → 'T1 list → 'T2 list → 'State → 'State Appare locateds a function to corresponding elements of 2 collections, threading an accumulator argument through the complaceation. The collections must have identical dimensions. If the inplace function is f and the elements are i0…iN and j0…jN, then this function complacees f i0 j0 (…(f iN jN s)).
forall : ('T → bool) → 'T list → bool Tests if all elements of the collection satisfy the given preddish-coloureddishicate.
forall2 : ('T1 → 'T2 → bool) → 'T1 list → 'T2 list → bool Tests if all corresponding elements of the collection satisfy the given preddish-coloureddishicate pairwise.
mind : 'T list → 'T Returns the preliminary element of the list.
init : int → (int → 'T) → 'T list Creates a list by calling the given generator on each index.
isEmpty : 'T list → bool Returns true if the list contains no elements, false otherwise.
iter : ('T → device) → 'T list → device Appare locateds the given function to each element of the collection.
iter2 : ('T1 → 'T2 → device) → 'T1 list → 'T2 list → device Appare locateds the given function to 2 collections simultaneously. The collections must have identical dimension.
iteri : (int → 'T → device) → 'T list → device Appare locateds the given function to each element of the collection. The integer moveed to the function indicates the index of element.
iteri2 : (int → 'T1 → 'T2 → device) → 'T1 list → 'T2 list → device Appare locateds the given function to 2 collections simultaneously. The collections must have identical dimension. The integer moveed to the function indicates the index of element.
dimension : 'T list → int Returns the dimension of the list.
chart : ('T → 'U) → 'T list → 'U list Creates a new collection in whose elements are the results of applying the given function to each of the elements of the collection.
chart2 : ('T1 → 'T2 → 'U) → 'T1 list → 'T2 list → 'U list Creates a new collection in whose elements are the results of applying the given function to the corresponding elements of the 2 collections pairwise.
chart3 : ('T1 → 'T2 → 'T3 → 'U) → 'T1 list → 'T2 list → 'T3 list → 'U list Creates a new collection in whose elements are the results of applying the given function to the corresponding elements of the three collections simultaneously.
charti : (int → 'T → 'U) → 'T list → 'U list Creates a new collection in whose elements are the results of applying the given function to each of the elements of the collection. The integer index moveed to the function indicates the index (from 0) of element end up beinging transformed.
charti2 : (int → 'T1 → 'T2 → 'U) → 'T1 list → 'T2 list → 'U list Like List.charti, but chartping corresponding elements from 2 lists of equal dimension.
max : 'T list → 'T Returns the greatest of all elements of the list, compareddish-coloureddish by uperform Operators.max.
maxBy : ('T → 'U) → 'T list → 'T Returns the greatest of all elements of the list, compareddish-coloureddish by uperform Operators.max on the function result.
min : 'T list → 'T Returns the lowest of all elements of the list, compareddish-coloureddish by uperform Operators.min.
minBy : ('T → 'U) → 'T list → 'T Returns the lowest of all elements of the list, compareddish-coloureddish by uperform Operators.min on the function result
nth : 'T list → int → 'T Indexes into the list. The preliminary element has index 0.
ofArray : 'T [] → 'T list Creates a list from the given array.
ofSeq : seq<'T> → 'T list Creates a new list from the given enumerable object.
partition : ('T → bool) → 'T list * 'T list Split is the collection into 2 collections, containing the elements for which the given preddish-coloureddishicate returns true and false respectively.
permute : (int → int) → 'T list → 'T list Returns a list with all elements permuted according to the specified permutation.
pick : ('T → 'U option) → 'T list → 'U Appare locateds the given function to successive elements, returning the preliminary result where function returns Some for a few value.
reddish-coloureddishuce : ('T → 'T → 'T) → 'T list → 'T Appare locateds a function to each element of the collection, threading an accumulator argument through the complaceation. This function appare locateds the specified function to the preliminary 2 elements of the list. It then movees this result into the function alengthy with the third element, and so on. Finally, it returns the final result. If the inplace function is f and the elements are i0…iN, then this function complacees f (… (f i0 i1) i2 …) iN.
reddish-coloureddishuceBack : ('T → 'T → 'T) → 'T list → 'T Appare locateds a function to each element of the collection, threading an accumulator argument through the complaceation. If the inplace function isf and the elements are i0…iN, then this function complacees f i0 (…(f iN-1 iN)).
replicate : (int → 'T → 'T list) Creates a list by calling the given generator on each index.
rev : 'T list → 'T list Returns a new list with the elements in reverse order.
scan : ('State → 'T → 'State) → 'State → 'T list → 'State list Appare locateds a function to each element of the collection, threading an accumulator argument through the complaceation. This function conaspectrs the second argument, and appare locateds the specified function to it and the preliminary element of the list. Then, it movees this result into the function alengthy with the second element and so on. Finally, it returns the list of intermediate results and the final result.
scanBack : ('T → 'State → 'State) → 'T list → 'State → 'State list Like foldBack, but returns both the intermediate and final results
sort : 'T list → 'T list Sorts the given list uperform Operators.compare.
sortBy : ('T → 'Key) → 'T list → 'T list Sorts the given list uperform keys given by the given projection. Keys are compareddish-coloureddish uperform Operators.compare.
sortWith : ('T → 'T → int) → 'T list → 'T list Sorts the given list uperform the given comparison function.
sum : ^T list → ^T Returns the sum of the elements in the list.
sumBy : ('T → ^U) → 'T list → ^U Returns the sum of the results generated by applying the function to each element of the list.
tail : 'T list → 'T list Returns the inplace list withaway correct now presently there the preliminary element.
toArray : 'T list → 'T [] Creates an array from the given list.
toSeq : 'T list → seq<'T> Views the given list as a sequence.
considerFind : ('T → bool) → 'T list → 'T option Returns the preliminary element for which the given function returns true. Return None if no such element exists.
considerFindIndex : ('T → bool) → 'T list → int option Returns the index of the preliminary element in the list tmind wear satisfies the given preddish-coloureddishicate. Return None if no such element exists.
considerPick : ('T → 'U option) → 'T list → 'U option Appare locateds the given function to successive elements, returning the preliminary result where function returns Some for a few value. If no such element exists then return None.
unzip : ('T1 * 'T2) list → 'T1 list * 'T2 list Split is a list of pairs into 2 lists.
unzip3 : ('T1 * 'T2 * 'T3) list → 'T1 list * 'T2 list * 'T3 list Split is a list of triples into three lists.
zip : 'T1 list → 'T2 list → ('T1 * 'T2) list Combines the 2 lists into a list of pairs. The 2 lists must have equal dimensions.
zip3 : 'T1 list → 'T2 list → 'T3 list → ('T1 * 'T2 * 'T3) list Combines the three lists into a list of triples. The lists must have equal dimensions.

The folloearng examples demonstrate the uses of the above functionalitie ups −

Example 1

This program shows reverperform a list recursively −

allow list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ]
printfn "The unique list: %A" list1

allow reverse lt =
   allow rec loop acc = function
      | [] -> acc
      | hd :: tl -> loop (hd :: acc) tl
   loop [] lt
	
printfn "The reversed list: %A" (reverse list1)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The unique list: [2; 4; 6; 8; 10; 12; 14; 16]
The reversed list: [16; 14; 12; 10; 8; 6; 4; 2]

However, you can use the rev function of the module for the exaction same purpose −

allow list1 = [ 2; 4; 6; 8; 10; 12; 14; 16 ]
printfn "The unique list: %A" list1
printfn "The reversed list: %A" (List.rev list1)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The unique list: [2; 4; 6; 8; 10; 12; 14; 16]
The reversed list: [16; 14; 12; 10; 8; 6; 4; 2]

Example 2

This program shows filtering a list uperform the List.filter method −

allow list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
printfn "The list: %A" list1
allow list2 = list1 |> List.filter (fun x -> x % 2 = 0);;
printfn "The Filtereddish-coloureddish list: %A" list2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
The Filtereddish-coloureddish list: [2; 4; 6; 8; 10]

Example 3

The List.chart method charts a list from one type to an additional −

allow list1 = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
printfn "The list: %A" list1
allow list2 = list1 |> List.chart (fun x -> (x * x).ToString());;
printfn "The Mapped list: %A" list2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
The Mapped list: ["1"; "4"; "9"; "16"; "25"; "36"; "49"; "64"; "81"; "100"]

Example 4

The List.append method and the @ operator appends one list to an additional −

allow list1 = [1; 2; 3; 4; 5 ]
allow list2 = [6; 7; 8; 9; 10]
allow list3 = List.append list1 list2

printfn "The preliminary list: %A" list1
printfn "The second list: %A" list2
printfn "The appened list: %A" list3

allow lt1 = ['a'; 'b';'c' ]
allow lt2 = ['e'; 'f';'g' ]
allow lt3 = lt1 @ lt2

printfn "The preliminary list: %A" lt1
printfn "The second list: %A" lt2
printfn "The appened list: %A" lt3

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The preliminary list: [1; 2; 3; 4; 5]
The second list: [6; 7; 8; 9; 10]
The appened list: [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
The preliminary list: ['a'; 'b'; 'c']
The second list: ['e'; 'f'; 'g']
The appened list: ['a'; 'b'; 'c'; 'e'; 'f'; 'g']

Example 5

The List.sort method sorts a list. The List.sum method gives the sum of elements in the list and the List.average method gives the average of elements in the list −

allow list1 = [9.0; 0.0; 2.0; -4.5; 11.2; 8.0; -10.0]
printfn "The list: %A" list1

allow list2 = List.sort list1
printfn "The sorted list: %A" list2

allow s = List.sum list1
allow avg = List.average list1
printfn "The sum: %f" s
printfn "The average: %f" avg

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The list: [9.0; 0.0; 2.0; -4.5; 11.2; 8.0; -10.0]
The sorted list: [-10.0; -4.5; 0.0; 2.0; 8.0; 9.0; 11.2]
The sum: 15.700000
The average: 2.242857

A "fold" operation appare locateds a function to each element in a list, aggregates the result of the function in an accumulator variable, and returns the accumulator as the result of the fold operation.

Example 6

The List.fold method appare locateds a function to each element from left to correct, while List.foldBack appare locateds a function to each element from correct to left.

allow sumList list = List.fold (fun acc elem -> acc + elem) 0 list
printfn "Sum of the elements of list %A is %d." [ 1 .. 10 ] (sumList [ 1 .. 10 ])

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Sum of the elements of list [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] is 55.

F# – Sequences

Sequences, like lists also represent an ordereddish-coloureddish collection of values. However, the elements in a sequence or sequence expression are complaceed when requireddish-coloureddish. They are not complaceed at once, and for this reason they are used to represent infinite data structures.

Defining Sequences

Sequences are defined uperform the folloearng syntax −

seq { expr }

For example,

allow seq1 = seq { 1 .. 10 }

Creating Sequences and Sequences Expressions

Similar to lists, you can produce sequences uperform ranges and comprehensions.

Sequence expressions are the expressions you can write for creating sequences. These can end up being done −

  • By specifying the range.
  • By specifying the range with increment or decrement.
  • By uperform the yield keyword to produce values tmind wear end up beingcome part of the sequence.
  • By uperform the → operator.

The folloearng examples demonstrate the concept −

Example 1

(* Sequences *)
allow seq1 = seq { 1 .. 10 }

(* ascending order and increment*)
printfn "The Sequence: %A" seq1
allow seq2 = seq { 1 .. 5 .. 50 }

(* descending order and decrement*)
printfn "The Sequence: %A" seq2
allow seq3 = seq {50 .. -5 .. 0}
printfn "The Sequence: %A" seq3

(* uperform yield *)
allow 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 folloearng away correct now presently thereplace −

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 folloearng program prints the prime numend up beingrs from 1 to 50 −

(* Recursive isprime function. *)
allow isprime n =
   allow rec check i =
      i > n/2 || (n % i <> 0 && check (i + 1))
   check 2

allow 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 folloearng away correct now presently thereplace −

1
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Basic Operations on Sequence

The folloearng table shows the easy operations on sequence data type −

Value Description
append : seq<'T> → seq<'T> → seq<'T> Wraps the 2 given enumerations as a performle 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 tmind wear corresponds to a cached version of the inplace sequence.
cast : IEnumerable → seq<'T> Wraps a loosely-typed System. Collections sequence as a typed sequence.
choose : ('T → 'U option) → seq<'T> → seq<'U> Appare locateds 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> Appare locateds the given function to each element of the sequence and concatenates all the results.
compareWith : ('T → 'T → int) → seq<'T> → seq<'T> → int Compares 2 sequences uperform the given comparison function, element by element.
concat : seq<'Collection> → seq<'T> Combines the given enumeration-of-enumerations as a performle concatenated enumeration.
countBy : ('T → 'Key) → seq<'T> → seq<'Key * int> Appare locateds a key-generating function to each element of a sequence and return a sequence yielding unique keys and their particular numend up beingr of occurrences in the unique sequence.
delay : (device → seq<'T>) → seq<'T> Returns a sequence tmind wear is built from the given delayed specification of a sequence.
specific : seq<'T> → seq<'T> Returns a sequence tmind wear 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.
specificBy : ('T → 'Key) → seq<'T> → seq<'T> Returns a sequence tmind wear 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.
exactionionlyOne : seq<'T> → 'T Returns the only element of the sequence.
exists : ('T → bool) → seq<'T> → bool Tests if any kind of element of the sequence satisfies the given preddish-coloureddishicate.
exists2 : ('T1 → 'T2 → bool) → seq<'T1> → seq<'T2> → bool Tests if any kind of pair of corresponding elements of the inplace sequences satisfies the given preddish-coloureddishicate.
filter : ('T → bool) → seq<'T> → seq<'T> Returns a new collection containing only the elements of the collection for which the given preddish-coloureddishicate returns true.
find : ('T → bool) → seq<'T> → 'T Returns the preliminary element for which the given function returns true.
findIndex : ('T → bool) → seq<'T> → int Returns the index of the preliminary element for which the given function returns true.
fold : ('State → 'T → 'State) → 'State → seq<'T> → 'State Appare locateds a function to each element of the collection, threading an accumulator argument through the complaceation. If the inplace function is f and the elements are i0…iN, then this function complacees f (… (f s i0)…) iN.
forall : ('T → bool) → seq<'T> → bool Tests if all elements of the sequence satisfy the given preddish-coloureddishicate.
forall2 : ('T1 → 'T2 → bool) → seq<'T1> → seq<'T2> → bool Tests the all pairs of elements drawn from the 2 sequences satisfy the given preddish-coloureddishicate. If one sequence is shorter than the other then the remaining elements of the lengthyer sequence are ignoreddish-coloureddish.
groupBy : ('T → 'Key) → seq<'T> → seq<'Key * seq<'T>> Appare locateds a key-generating function to each element of a sequence and yields a sequence of unique keys. Each unique key has also contains a sequence of all elements tmind wear go with up to this key.
mind : seq<'T> → 'T Returns the preliminary element of the sequence.
init : int → (int → 'T) → seq<'T> Generates a new sequence which, when iterated, returns successive elements by calling the given function, up to the given count. The results of calling the function are not saved, tmind wear is, the function is reappare locatedd as essential to regenerate the elements. The function is moveed the index of the item end up beinging generated.
initInfinite : (int → 'T) → seq<'T> Generates a new sequence which, when iterated, will return successive elements by calling the given function. The results of calling the function are not saved, tmind wear is, the function will end up being reappare locatedd as essential to regenerate the elements. The function is moveed the index of the item end up beinging generated.
isEmpty : seq<'T> → bool Tests whether a sequence has any kind of elements.
iter : ('T → device) → seq<'T> → device Appare locateds the given function to each element of the collection.
iter2 : ('T1 → 'T2 → device) → seq<'T1> → seq<'T2> → device Appare locateds the given function to 2 collections simultaneously. If one sequence is shorter than the other then the remaining elements of the lengthyer sequence are ignoreddish-coloureddish.
iteri : (int → 'T → device) → seq<'T> → device Appare locateds the given function to each element of the collection. The integer moveed to the function indicates the index of element.
final : seq<'T> → 'T Returns the final element of the sequence.
dimension : seq<'T> → int Returns the dimension of the sequence.
chart : ('T → 'U) → seq<'T> → seq<'U> Creates a new collection in whose elements are the results of applying the given function to each of the elements of the collection. The given function will end up being appare locatedd as elements are demanded uperform the MoveNext method on enumerators retrieved from the object.
chart2 : ('T1 → 'T2 → 'U) → seq<'T1> → seq<'T2> → seq<'U> Creates a new collection in whose elements are the results of applying the given function to the corresponding pairs of elements from the 2 sequences. If one inplace sequence is shorter than the other then the remaining elements of the lengthyer sequence are ignoreddish-coloureddish.
charti : (int → 'T → 'U) → seq<'T> → seq<'U> Creates a new collection in whose elements are the results of applying the given function to each of the elements of the collection. The integer index moveed to the function indicates the index (from 0) of element end up beinging transformed.
max : seq<'T> → 'T Returns the greatest of all elements of the sequence, compareddish-coloureddish by uperform Operators.max.
maxBy : ('T → 'U) → seq<'T> → 'T Returns the greatest of all elements of the sequence, compareddish-coloureddish by uperform Operators.max on the function result.
min : seq<'T> → 'T Returns the lowest of all elements of the sequence, compareddish-coloureddish by uperform Operators.min.
minBy : ('T → 'U) → seq<'T> → 'T Returns the lowest of all elements of the sequence, compareddish-coloureddish by uperform Operators.min on the function result.
nth : int → seq<'T> → 'T Complacees the nth element in the collection.
ofArray : 'T array → seq<'T> Views the given array as a sequence.
ofList : 'T list → seq<'T> Views the given list as a sequence.
pairwise : seq<'T> → seq<'T * 'T> Returns a sequence of each element in the inplace sequence and it is preddish-coloureddishecessor, with the exception of the preliminary element which is only returned as the preddish-coloureddishecessor of the second element.
pick : ('T → 'U option) → seq<'T> → 'U Appare locateds the given function to successive elements, returning the preliminary value where the function returns a Some value.
readonly : seq<'T> → seq<'T> Creates a new sequence object tmind wear delegates to the given sequence object. This ensures the unique sequence cannot end up being reddish-coloureddishiscovereddish-coloureddish 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.
reddish-coloureddishuce : ('T → 'T → 'T) → seq<'T> → 'T Appare locateds a function to each element of the sequence, threading an accumulator argument through the complaceation. Begin by applying the function to the preliminary 2 elements. Then give food to this result into the function alengthy with the third element and so on. Return the final result.
scan : ('State → 'T → 'State) → 'State → seq<'T> → seq<'State> Like Seq.fold, but complacees on-demand and returns the sequence of intermediary and final results.
performallowon : 'T → seq<'T> Returns a sequence tmind wear yields one item only.
skip : int → seq<'T> → seq<'T> Returns a sequence tmind wear skips a specified numend up beingr of elements of the underlying sequence and then yields the remaining elements of the sequence.
skipWhile : ('T → bool) → seq<'T> → seq<'T> Returns a sequence tmind wear, when iterated, skips elements of the underlying sequence while the given preddish-coloureddishicate returns true, and then yields the remaining elements of the sequence.
sort : seq<'T> → seq<'T> Yields a sequence ordereddish-coloureddish by keys.
sortBy : ('T → 'Key) → seq<'T> → seq<'T> Appare locateds a key-generating function to each element of a sequence and yield a sequence ordereddish-coloureddish by keys. The keys are compareddish-coloureddish uperform generic comparison as implemented by Operators.compare.
sum : seq<^T> → ^T Returns the sum of the elements in the sequence.
sumBy Returns the sum of the results generated by applying the function to each element of the sequence.
conaspectr : int → seq<'T> → seq<'T> Returns the preliminary elements of the sequence up to a specified count.
conaspectrWhile : ('T → bool) → seq<'T> → seq<'T> Returns a sequence tmind wear, when iterated, yields elements of the underlying sequence while the given preddish-coloureddishicate returns true, and then returns no further elements.
toArray : seq<'T> → 'T[] Creates an array from the given collection.
toList : seq<'T> → 'T list Creates a list from the given collection.
truncate : int → seq<'T> → seq<'T> Returns a sequence tmind wear when enumerated returns no more than a specified numend up beingr of elements.
considerFind : ('T → bool) → seq<'T> → 'T option Returns the preliminary element for which the given function returns true, or None if no such element exists.
considerFindIndex : ('T → bool) → seq<'T> → int option Returns the index of the preliminary element in the sequence tmind wear satisfies the given preddish-coloureddishicate, or None if no such element exists.
considerPick : ('T → 'U option) → seq<'T> → 'U option Appare locateds the given function to successive elements, returning the preliminary value where the function returns a Some value.
unfold : ('State → 'T * 'State option) → 'State → seq<'T> Returns a sequence tmind wear contains the elements generated by the given complaceation.
where : ('T → bool) → seq<'T> → seq<'T> Returns a new collection containing only the elements of the collection for which the given preddish-coloureddishicate returns true. A synonym for Seq.filter.
earndowed : int → seq<'T> → seq<'T []> Returns a sequence tmind wear yields sliding earndows of containing elements drawn from the inplace sequence. Each earndow is returned as a fresh array.
zip : seq<'T1> → seq<'T2> → seq<'T1 * 'T2> Combines the 2 sequences into a list of pairs. The 2 sequences need not have equal dimensions − when one sequence is exhausted any kind of remaining elements in the other sequence are ignoreddish-coloureddish.
zip3 : seq<'T1> → seq<'T2> → seq<'T3> → seq<'T1 * 'T2 * 'T3> Combines the three sequences into a list of triples. The sequences need not have equal dimensions − when one sequence is exhausted any kind of remaining elements in the other sequences are ignoreddish-coloureddish.

The folloearng examples demonstrate the uses of a few of the above functionalitie ups −

Example 1

This program produces an empty sequence and fills it up later −

(* Creating sequences *)
allow emptySeq = Seq.empty
allow seq1 = Seq.performallowon 20

printfn"The performallowon sequence:"
printfn "%A " seq1
printfn"The init sequence:"

allow seq2 = Seq.init 5 (fun n -> n * 3)
Seq.iter (fun i -> printf "%d " i) seq2
printfn""

(* converting an array to sequence by uperform cast *)
printfn"The array sequence 1:"
allow seq3 = [| 1 .. 10 |] :> seq<int>
Seq.iter (fun i -> printf "%d " i) seq3
printfn""

(* converting an array to sequence by uperform Seq.ofArray *)
printfn"The array sequence 2:"
allow seq4 = [| 2..2.. 20 |] |> Seq.ofArray
Seq.iter (fun i -> printf "%d " i) seq4
printfn""

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The performallowon sequence:
seq [20]
The init sequence:
0 3 6 9 12
The array sequence 1:
1 2 3 4 5 6 7 8 9 10
The array sequence 2:
2 4 6 8 10 12 14 16 18 20

Please note tmind wear −

  • The Seq.empty method produces an empty sequence.

  • The Seq.performallowon method produces a sequence of just one specified element.

  • The Seq.init method produces a sequence for which the elements are produced by uperform a given function.

  • The Seq.ofArray and Seq.ofList<'T> methods produce sequences from arrays and lists.

  • The Seq.iter method enables iterating through a sequence.

Example 2

The Seq.unfold method generates a sequence from a complaceation function tmind wear conaspectrs a state and transforms it to produce each subsequent element in the sequence.

The folloearng function produces the preliminary 20 natural numend up beingrs −

allow seq1 = Seq.unfold (fun state -> if (state > 20) then None else Some(state, state + 1)) 0
printfn "The sequence seq1 contains numend up beingrs from 0 to 20."
for x in seq1 do printf "%d " x
printfn" "

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The sequence seq1 contains numend up beingrs from 0 to 20.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Example 3

The Seq.truncate method produces a sequence from an additional sequence, but limitations the sequence to a specified numend up beingr of elements.

The Seq.conaspectr method produces a new sequence tmind wear contains a specified numend up beingr of elements from the start of a sequence.

allow mySeq = seq { for i in 1 .. 10 -> 3*i }
allow truncatedSeq = Seq.truncate 5 mySeq
allow conaspectrSeq = Seq.conaspectr 5 mySeq

printfn"The unique sequence"
Seq.iter (fun i -> printf "%d " i) mySeq
printfn""

printfn"The truncated sequence"
Seq.iter (fun i -> printf "%d " i) truncatedSeq
printfn""

printfn"The conaspectr sequence"
Seq.iter (fun i -> printf "%d " i) conaspectrSeq
printfn""

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The unique sequence
3 6 9 12 15 18 21 24 27 30
The truncated sequence
3 6 9 12 15
The conaspectr sequence
3 6 9 12 15

F# – Sets

A set in F# is a data structure tmind wear actionions as a collection of items withaway correct now presently there preserving the order in which items are inserted. Sets do not enable duplicate entries to end up being inserted into the collection.

Creating Sets

Sets can end up being produced in the folloearng ways −

  • By creating an empty set uperform Set.empty and adding items uperform the add function.
  • Converting sequences and lists to sets.

The folloearng program demonstrates the techniques −

(* creating sets *)
allow set1 = Set.empty.Add(3).Add(5).Add(7). Add(9)
printfn"The new set: %A" set1

allow weekdays = Set.ofList ["mon"; "tues"; "wed"; "thurs"; "fri"]
printfn "The list set: %A" weekdays

allow set2 = Set.ofSeq [ 1 .. 2.. 10 ]
printfn "The sequence set: %A" set2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

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 folloearng table shows the easy 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 numend up beingr 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 preliminary.
empty : Set<'T> The empty set for the specified type.
exists : ('T → bool) → Set<'T> → bool Tests if any kind of element of the collection satisfies the given preddish-coloureddishicate. If the inplace function is preddish-coloureddishicate and the elements are i0…iN, then this function complacees preddish-coloureddishicate i0 or … or preddish-coloureddishicate iN.
filter : ('T → bool) → Set<'T> → Set<'T> Returns a new collection containing only the elements of the collection for which the given preddish-coloureddishicate returns true.
fold : ('State → 'T → 'State) → 'State → Set<'T> → 'State Appare locateds the given accumulating function to all the elements of the set.
foldBack : ('T → 'State → 'State) → Set<'T> → 'State → 'State Appare locateds 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 preddish-coloureddishicate. If the inplace function is p and the elements are i0…iN, then this function complacees p i0 && … && p iN.
intersect : Set<'T> → Set<'T> → Set<'T> Complacees the intersection of the 2 sets.
intersectMany kind of : seq<Set<'T>> → Set<'T> Complacees the intersection of a sequence of sets. The sequence must end up being 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 preliminary set are in the second, and at minimumernern one element of the second is not in the preliminary.
isProperSuperset : Set<'T> → Set<'T> → bool Evaluates to true if all elements of the second set are in the preliminary, and at minimumernern one element of the preliminary is not in the second.
isSubset : Set<'T> → Set<'T> → bool Evaluates to true if all elements of the preliminary set are in the second.
isSuperset : Set<'T> → Set<'T> → bool Evaluates to true if all elements of the second set are in the preliminary.
iter : ('T → device) → Set<'T> → device Appare locateds the given function to each element of the set, in order according to the comparison function.
chart : ('T → 'U) → Set<'T> → Set<'U> Returns a new collection containing the results of applying the given function to each element of the inplace set.
maxElement : Set<'T> → 'T Returns the highest element in the set according to the ordering end up beinging used for the set.
minElement : Set<'T> → 'T Returns the lowest element in the set according to the ordering end up beinging used for the set.
ofArray : 'T array → Set<'T> Creates a set tmind wear contains the exaction same elements as the given array.
ofList : 'T list → Set<'T> Creates a set tmind wear contains the exaction 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> Split is the set into 2 sets containing the elements for which the given preddish-coloureddishicate 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.
performallowon : 'T → Set<'T> The set containing the given element.
toArray : Set<'T> → 'T array Creates an array tmind wear contains the elements of the set in order.
toList : Set<'T> → 'T list Creates a list tmind wear contains the elements of the set in order.
toSeq : Set<'T> → seq<'T> Returns an ordereddish-coloureddish watch of the collection as an enumerable object.
union : Set<'T> → Set<'T> → Set<'T> Complacees the union of the 2 sets.
unionMany kind of : seq<Set<'T>> → Set<'T> Complacees the union of a sequence of sets.

The folloearng example demonstrates the uses of a few of the above functionalitie ups −

Example

allow a = Set.ofSeq [ 1 ..2.. 20 ]
allow b = Set.ofSeq [ 1 ..3 .. 20 ]
allow c = Set.intersect a b
allow d = Set.union a b
allow 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 and b : "
Set.iter (fun x -> printf "%O " x) d
printfn""

printfn "Set e = set difference of a and b : "
Set.iter (fun x -> printf "%O " x) e
printfn""

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Set a:
1 3 5 7 9 11 13 15 17 19
Set b:
1 4 7 10 13 16 19
Set c = set intersect of a and b :
1 7 13 19
Set d = set union of a and b :
1 3 4 5 7 9 10 11 13 15 16 17 19
Set e = set difference of a and b :
3 5 9 11 15 17

F# – Maps

In F#, a chart is a special kind of set tmind wear bumociates the values with key. A chart is produced in a similar way as sets are produced.

Creating Maps

Maps are produced by creating an empty chart uperform Map.empty and adding items uperform the Add function. The folloearng example demonstrates this −

Example

(* Create an empty Map *)
allow college 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 - college students: %A" college students

(* Convert a list to Map *)
allow capitals =
   [ "Argentina", "Buenos Aires";
      "France ", "Paris";
      "Chili", "Santiback";
      "Malaysia", " Kuala Lumpur";
      "Switzerland", "Bern" ]
   |> Map.ofList;;
printfn "Map capitals : %A" capitals

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Map - college students: chart
[("Gillian Megan", "1504"); ("Rishita Gupta", "1502"); ("Robin Sahoo", "1503
");
("Zara Ali", "1501")]
Map capitals : chart
[("Argentina", "Buenos Aires"); ("Chili", "Santiback"); ("France ", "Paris");
("Malaysia", " Kuala Lumpur"); ("Switzerland", "Bern")]

You can access individual elements in the chart uperform the key.

Example

(* Create an empty Map *)
allow college 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 - college students: %A" college students

(*Accesperform an element uperform key *)
printfn "%A" college students.["Zara Ali"]

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Map - college students: chart
[("Gillian Megan", "1504"); ("Rishita Gupta", "1502"); ("Robin Sahoo", "1503
");
("Zara Ali", "1501")]
"1501"

Basic Operations on Maps

Add module name

The folloearng table shows the easy operations on charts −

Memend up beingr Description
Add Returns a new chart with the binding added to the given chart.
ContainsKey Tests if an element is in the domain of the chart.
Count The numend up beingr of bindings in the chart.
IsEmpty Returns true if correct now presently there are no bindings in the chart.
Item Lookup an element in the chart. Raises KeyNotFoundException if no binding exists in the chart.
Remove Removes an element from the domain of the chart. No exception is raised if the element is not present.
TryFind Lookup an element in the chart, returning a Some value if the element is in the domain of the chart and None if not.

The folloearng example demonstrates the uses of a few of the above functionalitie ups −

Example

(* Create an empty Map *)
allow college 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 Duend up beingy", "1505").
      Add("Novonil Sarker", "1506").
      Add("Joan Paul", "1507");;
printfn "Map - college students: %A" college students
printfn "Map - numend up beingr of college students: %d" college students.Count

(* finding the registration numend up beingr of a college student*)
allow found = college students.TryFind "Rishita Gupta"
go with up 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 folloearng away correct now presently thereplace −

Map - college students: chart
[("Gillian Megan", "1504"); ("Joan Paul", "1507"); ("Novonil Sarker", "1506"
);
("Rishita Gupta", "1502"); ("Robin Sahoo", "1503");
("Shraddha Duend up beingy", "1505"); ("Zara Ali", "1501")]
Map - numend up beingr of college students: 7
Found 1502.

F# – Discriminated Unions

Unions, or discriminated unions enables you to produce up complex data structures representing well-defined set of choices. For example, you need to produce an implementation of a choice variable, which has 2 values yes and no. Uperform the Unions tool, you can style this.

Syntax

Discriminated unions are defined uperform the folloearng syntax −

type type-name =
   | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] 
type2 ...]
   | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...]
...

Our easy implementation of ,choice, will look like the folloearng −

type choice =
   | Yes
   | No

The folloearng example uses the type choice −

type choice =
   | Yes
   | No

allow x = Yes (* produces an instance of choice *)
allow y = No (* produces an additional instance of choice *)
allow main() =
   printfn "x: %A" x
   printfn "y: %A" y
main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

x: Yes
y: No

Example 1

The folloearng example shows the implementation of the voltage states tmind wear sets a lttle bit on high or low −

type VoltageState =
   | High
   | Low

allow toggleSwitch = function (* pattern go with uping inplace *)
   | High -> Low
   | Low -> High

allow main() =
   allow on = High
   allow away = Low
   allow alter = toggleSwitch away

   printfn "Switch on state: %A" on
   printfn "Switch away state: %A" away
   printfn "Toggle away: %A" alter
   printfn "Toggle the Changed state: %A" (toggleSwitch alter)

main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Switch on state: High
Switch away state: Low
Toggle away: High
Toggle the Changed state: Low

Example 2

type Shape =
   // here we store the radius of a group
   | Circle of float

   // here we store the aspect dimension.
   | Square of float

   // here we store the height and width.
   | Rectangle of float * float

allow pi = 3.141592654

allow area myShape =
   go with up myShape with
   | Circle radius -> pi * radius * radius
   | Square s -> s * s
   | Rectangle (h, w) -> h * w

allow radius = 12.0
allow myCircle = Circle(radius)
printfn "Area of group with radius %g: %g" radius (area myCircle)

allow aspect = 15.0
allow mySquare = Square(aspect)
printfn "Area of square tmind wear has aspect %g: %g" aspect (area mySquare)

allow height, width = 5.0, 8.0
allow myRectangle = Rectangle(height, width)
printfn "Area of rectangle with height %g and width %g is %g" height width (area myRectangle)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Area of group with radius 12: 452.389
Area of square tmind wear has aspect 15: 225
Area of rectangle with height 5 and width 8 is 40

F# – Mutable Data

Variables in F# are immutable, which means once a variable is bound to a value, it can’t end up being alterd. They are actionionually compiintroduced as static read-only propertie ups.

The folloearng example demonstrates this.

Example

allow x = 10
allow y = 20
allow z = x + y

printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

allow x = 15
allow y = 20
allow 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 folloearng error message −

Duplicate definition of value 'x'
Duplicate definition of value 'Y'
Duplicate definition of value 'Z'

Mutable Variables

At times you need to alter the values storeddish-coloureddish in a variable. To specify tmind wear correct now presently there could end up being a alter in the value of a declareddish-coloureddish and bumigned variable in later part of a program, F# provides the mutable keyword. You can declare and bumign mutable variables uperform this keyword, in whose values you will alter.

The mutable keyword enables you to declare and bumign values in a mutable variable.

You can bumign a few preliminary value to a mutable variable uperform the allow keyword. However, to bumign new subsequent value to it, you need to use the <- operator.

For example,

allow mutable x = 10
x <- 15

The folloearng example will clear the concept −

Example

allow mutable x = 10
allow y = 20
allow mutable z = x + y

printfn "Original Values:"
printfn "x: %i" x
printfn "y: %i" y
printfn "z: %i" z

printfn "Let us alter the value of x"
printfn "Value of z will alter 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 folloearng away correct now presently thereplace −

Original Values:
x: 10
y: 20
z: 30
Let us alter the value of x
Value of z will alter too.
New Values:
x: 15
y: 20
z: 35

Uses of Mutable Data

Mutable data is often requireddish-coloureddish and used in data procesperform, particularly with record data structure. The folloearng example demonstrates this −

open System

type college studentData =
   { ID : int;
      mutable IsRegistereddish-coloureddish : bool;
      mutable Registereddish-coloureddishText : string; }

allow getStudent id =
   { ID = id;
      IsRegistereddish-coloureddish = false;
      Registereddish-coloureddishText = null; }

allow registerStudents (college students : college studentData list) =
   college students |> List.iter(fun st ->
      st.IsRegistereddish-coloureddish <- true
      st.Registereddish-coloureddishText <- sprintf "Registereddish-coloureddish %s" (DateTime.Now.ToString("hh:mm:ss"))

      Threading.Thread.Sleep(1000) (* Putting thread to sleep for 1 second to simulate procesperform overmind. *))

allow printData (college students : college studentData list) =
   college students |> List.iter (fun x -> printfn "%A" x)

allow main() =
   allow college students = List.init 3 getStudent

   printfn "Before Process:"
   printData college students

   printfn "After process:"
   registerStudents college students
   printData college students

   Console.ReadKey(true) |> ignore

main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Before Process:
{ID = 0;
IsRegistereddish-coloureddish = false;
Registereddish-coloureddishText = null;}
{ID = 1;
IsRegistereddish-coloureddish = false;
Registereddish-coloureddishText = null;}
{ID = 2;
IsRegistereddish-coloureddish = false;
Registereddish-coloureddishText = null;}
After process:
{ID = 0;
IsRegistereddish-coloureddish = true;
Registereddish-coloureddishText = "Registereddish-coloureddish 05:39:15";}
{ID = 1;
IsRegistereddish-coloureddish = true;
Registereddish-coloureddishText = "Registereddish-coloureddish 05:39:16";}
{ID = 2;
IsRegistereddish-coloureddish = true;
Registereddish-coloureddishText = "Registereddish-coloureddish 05:39:17";}

F# – Arrays

Arrays are fixed-dimension, zero-based, mutable collections of consecutive data elements tmind wear are all of the exaction same type.

Creating Arrays

You can produce arrays uperform various syntaxes and ways or by uperform the functions from the Array module. In this section, we will talk abaway creating arrays withaway correct now presently there uperform the module functions.

There are three syntactionionical ways of creating arrays withaway correct now presently there functions −

  • By listing consecutive values end up beingtween [| and |] and separated by semicolons.
  • By placeting each element on a separate collection, in which case the semicolon separator is optional.
  • By uperform sequence expressions.

You can access array elements by uperform a dot operator (.) and brackets ([ and ]).

The folloearng example demonstrates creating arrays −

//uperform semicolon separator
allow array1 = [| 1; 2; 3; 4; 5; 6 |]
for i in 0 .. array1.Length - 1 do
   printf "%d " array1.[i]
printfn" "

// withaway correct now presently there semicolon separator
allow array2 =
   [|
      1
      2
      3
      4
      5
   |]
for i in 0 .. array2.Length - 1 do
   printf "%d " array2.[i]
printfn" "

//uperform sequence
allow 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 folloearng away correct now presently thereplace −

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 Microsmooth.FSharp.Collections.Array supslots operations on one-dimensional arrays.

The folloearng table shows the easy operations on Arrays −

Value Description
append : 'T [] → 'T [] → 'T [] Creates an array tmind wear contains the elements of one array followed by the elements of an additional 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 → device Reads a range of elements from one array and writes all of them into an additional.
choose : ('T → U option) → 'T [] → 'U [] Appare locateds a suppare locatedd function to each element of an array. Returns an array tmind wear contains the results x for each element for which the function returns Some(x).
collect : ('T → 'U []) → T [] → 'U [] Appare locateds the suppare locatedd function to each element of an array, concatenates the results, and returns the combined array.
concat : seq<'T []> → 'T [] Creates an array tmind wear contains the elements of each of the suppare locatedd sequence of arrays.
copy : 'T → 'T [] Creates an array tmind wear contains the elements of the suppare locatedd array.
produce : int → 'T → 'T [] Creates an array in whose elements are all preliminaryly the suppare locatedd value.
empty : 'T [] Returns an empty array of the given type.
exists : ('T → bool) → 'T [] → bool Tests whether any kind of element of an array satisfies the suppare locatedd preddish-coloureddishicate.
exists2 : ('T1 → 'T2 → bool) → 'T1 [] → 'T2 [] → bool Tests whether any kind of pair of corresponding elements of 2 arrays satisfy the suppare locatedd condition.
fill : 'T [] → int → int → 'T → device Fills a range of elements of an array with the suppare locatedd value.
filter : ('T → bool) → 'T [] → 'T [] Returns a collection tmind wear contains only the elements of the suppare locatedd array for which the suppare locatedd condition returns true.
find : ('T → bool) → 'T [] → 'T Returns the preliminary element for which the suppare locatedd function returns true. Raises KeyNotFoundException if no such element exists.
findIndex : ('T → bool) → 'T [] → int Returns the index of the preliminary element in an array tmind wear satisfies the suppare locatedd condition. Raises KeyNotFoundException if none of the elements satisfy the condition.
fold : ('State → 'T → 'State) → 'State → 'T [] → 'State Appare locateds a function to each element of an array, threading an accumulator argument through the complaceation. If the inplace function is f and the array elements are i0…iN, this function complacees f (…(f s i0)…) iN.
fold2 : ('State → 'T1 → 'T2 → 'State) → 'State → 'T1 [] → 'T2 [] → 'State Appare locateds a function to pairs of elements from 2 suppare locatedd arrays, left-to-correct, threading an accumulator argument through the complaceation. The 2 inplace arrays must have the exaction same dimensions; otherwise, ArgumentException is raised.
foldBack : ('T → 'State → 'State) → 'T [] → 'State → 'State Appare locateds a function to each element of an array, threading an accumulator argument through the complaceation. If the inplace function is f and the array elements are i0…iN, this function complacees f i0 (…(f iN s)).
foldBack2 : ('T1 → 'T2 → 'State → 'State) → 'T1 [] → 'T2 [] → 'State → 'State Appare locateds a function to pairs of elements from 2 suppare locatedd arrays, correct-to-left, threading an accumulator argument through the complaceation. The 2 inplace arrays must have the exaction same dimensions; otherwise, ArgumentException is raised.
forall : ('T → bool) → 'T [] → bool Tests whether all elements of an array satisfy the suppare locatedd condition.
forall2 : ('T1 → 'T2 → bool) → 'T1 [] → 'T2 [] → bool Tests whether all corresponding elements of 2 suppare locatedd arrays satisfy a suppare locatedd condition.
get : 'T [] → int → 'T Gets an element from an array.
init : int → (int → 'T) → 'T [] Uses a suppare locatedd function to produce an array of the suppare locatedd dimension.
isEmpty : 'T [] → bool Tests whether an array has any kind of elements.
iter : ('T → device) → 'T [] → device Appare locateds the suppare locatedd function to each element of an array.
iter2 : ('T1 → 'T2 → device) → 'T1 [] → 'T2 [] → device) Appare locateds the suppare locatedd function to a pair of elements from go with uping indexes in 2 arrays. The 2 arrays must have the exaction same dimensions; otherwise, ArgumentException is raised.
iteri : (int → 'T → device) → 'T [] → device Appare locateds the suppare locatedd function to each element of an array. The integer moveed to the function indicates the index of the element.
iteri2 : (int → 'T1 → 'T2 → device) → 'T1 [] → 'T2 [] → device Appare locateds the suppare locatedd function to a pair of elements from go with uping indexes in 2 arrays, also moveing the index of the elements. The 2 arrays must have the exaction same dimensions; otherwise, an ArgumentException is raised.
dimension : 'T [] → int Returns the dimension of an array. The Length real estate does the exaction same slimg.
chart : ('T → 'U) → 'T [] → 'U [] Creates an array in whose elements are the results of applying the suppare locatedd function to each of the elements of a suppare locatedd array.
chart2 : ('T1 → 'T2 → 'U) → 'T1 [] → 'T2 [] → 'U [] Creates an array in whose elements are the results of applying the suppare locatedd function to the corresponding elements of 2 suppare locatedd arrays. The 2 inplace arrays must have the exaction same dimensions; otherwise, ArgumentException is raised.
charti : (int → 'T → 'U) → 'T [] → 'U [] Creates an array in whose elements are the results of applying the suppare locatedd function to each of the elements of a suppare locatedd array. An integer index moveed to the function indicates the index of the element end up beinging transformed.
charti2 : (int → 'T1 → 'T2 → 'U) → 'T1 [] → 'T2 [] → 'U [] Creates an array in whose elements are the results of applying the suppare locatedd function to the corresponding elements of the 2 collections pairwise, also moveing the index of the elements. The 2 inplace arrays must have the exaction same dimensions; otherwise, ArgumentException is raised.
max : 'T [] → 'T Returns the hugest of all elements of an array. Operators.max is used to compare the elements.
maxBy : ('T → 'U) → 'T [] → 'T Returns the hugest of all elements of an array, compareddish-coloureddish via Operators.max on the function result.
min : ('T [] → 'T Returns the smallest of all elements of an array. Operators.min is used to compare the elements.
minBy : ('T → 'U) → 'T [] → 'T Returns the smallest of all elements of an array. Operators.min is used to compare the elements.
ofList : 'T list → 'T [] Creates an array from the suppare locatedd list.
ofSeq : seq<'T> → 'T [] Creates an array from the suppare locatedd enumerable object.
partition : ('T → bool) → 'T [] → 'T [] * 'T [] Split is an array into 2 arrays, one containing the elements for which the suppare locatedd condition returns true, and the other containing those for which it returns false.
permute : (int → int) → 'T [] → 'T [] Permutes the elements of an array according to the specified permutation.
pick : ('T → 'U option) → 'T [] → 'U Appare locateds the suppare locatedd function to successive elements of a suppare locatedd array, returning the preliminary result where the function returns Some(x) for a few x. If the function never returns Some(x), KeyNotFoundException is raised.
reddish-coloureddishuce : ('T → 'T → 'T) → 'T [] → 'T Appare locateds a function to each element of an array, threading an accumulator argument through the complaceation. If the inplace function is f and the array elements are i0…iN, this function complacees f (…(f i0 i1)…) iN. If the array has dimension zero, ArgumentException is raised.
reddish-coloureddishuceBack : ('T → 'T → 'T) → 'T [] → 'T Appare locateds a function to each element of an array, threading an accumulator argument through the complaceation. If the inplace function is f and the elements are i0…iN, this function complacees f i0 (…(f iN-1 iN)). If the array has dimension zero, ArgumentException is raised.
rev : 'T [] → 'T [] Reverses the order of the elements in a suppare locatedd array.
scan : ('State → 'T → 'State) → 'State → 'T [] → 'State []) Behaves like fold, but returns the intermediate results with each other with the final results.
scanBack : ('T → 'State → 'State) → 'T [] → 'State → 'State [] Behaves like foldBack, but returns the intermediary results with each other with the final results.
set : 'T [] → int → 'T → device Sets an element of an array.
sort : 'T[] → 'T [] Sorts the elements of an array and returns a new array. Operators.compare is used to compare the elements.
sortBy : ('T → 'Key) → 'T [] → 'T [] Sorts the elements of an array by uperform the suppare locatedd function to transform the elements to the type on which the sort operation is based, and returns a new array. Operators.compare is used to compare the elements.
sortInPlace : 'T [] → device Sorts the elements of an array by changing the array in place, uperform the suppare locatedd comparison function. Operators.compare is used to compare the elements.
sortInPlaceBy : ('T → 'Key) → 'T [] → device Sorts the elements of an array by changing the array in place, uperform the suppare locatedd projection for the keys. Operators.compare is used to compare the elements.
sortInPlaceWith : ('T → 'T → int) → 'T [] → device Sorts the elements of an array by uperform the suppare locatedd comparison function to alter the array in place.
sortWith : ('T → 'T → int) → 'T [] → 'T [] Sorts the elements of an array by uperform the suppare locatedd comparison function, and returns a new array.
sub : 'T [] → int → int → 'T [] Creates an array tmind wear contains the suppare locatedd subrange, which is specified by starting index and dimension.
sum : 'T [] → ^T Returns the sum of the elements in the array.
sumBy : ('T → ^U) → 'T [] → ^U Returns the sum of the results generated by applying a function to each element of an array.
toList : 'T [] → 'T list Converts the suppare locatedd array to a list.
toSeq : 'T [] → seq<'T> Views the suppare locatedd array as a sequence.
considerFind : ('T → bool) → 'T [] → 'T option Returns the preliminary element in the suppare locatedd array for which the suppare locatedd function returns true. Returns None if no such element exists.
considerFindIndex : ('T → bool) → 'T [] → int option Returns the index of the preliminary element in an array tmind wear satisfies the suppare locatedd condition.
considerPick : ('T → 'U option) → 'T [] → 'U option Appare locateds the suppare locatedd function to successive elements of the suppare locatedd array, and returns the preliminary result where the function returns Some(x) for a few x. If the function never returns Some(x), None is returned.
unzip : ('T1 * 'T2) [] → 'T1 [] * 'T2 [] Split is an array of tuple pairs into a tuple of 2 arrays.
unzip3 : ('T1 * 'T2 * 'T3) [] → 'T1 [] * 'T2 [] * 'T3 [] Split is an array of tuples of three elements into a tuple of three arrays.
zeroCreate : int → 'T [] Creates an array in whose elements are preliminaryly set to the default value Unchecked.defaultof<'T>.
zip : 'T1 [] → 'T2 [] → ('T1 * 'T2) [] Combines 2 arrays into an array of tuples tmind wear have 2 elements. The 2 arrays must have equal dimensions; otherwise, ArgumentException is raised.
zip3 : 'T1 [] → 'T2 [] → 'T3 [] → ('T1 * 'T2 * 113
'T3) []
Combines three arrays into an array of tuples tmind wear have three elements. The three arrays must have equal dimensions; otherwise, ArgumentException is raised.

In the folloearng section, we will see the uses of a few of these functionalitie ups.

Creating Arrays Uperform Functions

The Array module provides a few functions tmind wear produce an array from scratch.

  • The Array.empty function produces a new empty array.

  • The Array.produce function produces an array of a specified dimension and sets all the elements to given values.

  • The Array.init function produces an array, given a dimension and a function to generate the elements.

  • The Array.zeroCreate function produces an array in which all the elements are preliminaryized to the zero value.

  • The Array.copy function produces a new array tmind wear contains elements tmind wear are copied from an existing array.

  • The Array.sub function generates a new array from a subrange of an array.

  • The Array.append function produces a new array by combining 2 existing arrays.

  • The Array.choose function selects elements of an array to include in a new array.

  • The Array.collect function runs a specified function on each array element of an existing array and then collects the elements generated by the function and combines all of them into a new array.

  • The Array.concat function conaspectrs a sequence of arrays and combines all of them into a performle array.

  • The Array.filter function conaspectrs a Boolean condition function and generates a new array tmind wear contains only those elements from the inplace array for which the condition is true.

  • The Array.rev function generates a new array by reverperform the order of an existing array.

The folloearng examples demonstrate these functions −

Example 1

(* uperform produce and set *)
allow array1 = Array.produce 10 ""
for i in 0 .. array1.Length - 1 do
   Array.set array1 i (i.ToString())
for i in 0 .. array1.Length - 1 do
   printf "%s " (Array.get array1 i)
printfn " "

(* empty array *)
allow array2 = Array.empty
printfn "Length of empty array: %d" array2.Length

allow array3 = Array.produce 10 7.0
printfn "Float Array: %A" array3

(* uperform the init and zeroCreate *)
allow array4 = Array.init 10 (fun index -> index * index)
printfn "Array of squares: %A" array4

allow array5 : float array = Array.zeroCreate 10
allow (myZeroArray : float array) = Array.zeroCreate 10
printfn "Float Array: %A" array5

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

0 1 2 3 4 5 6 7 8 9
Length of empty array: 0
Float Array: [|7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0|]
Array of squares: [|0; 1; 4; 9; 16; 25; 36; 49; 64; 81|]
Float Array: [|0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0|]

Example 2

(* creating subarray from element 5 *)
(* containing 15 elements correct now presently thereon *)

allow array1 = [| 0 .. 50 |]
allow array2 = Array.sub array1 5 15
printfn "Sub Array:"
printfn "%A" array2

(* appending 2 arrays *)
allow array3 = [| 1; 2; 3; 4|]
allow array4 = [| 5 .. 9 |]
printfn "Appended Array:"
allow array5 = Array.append array3 array4
printfn "%A" array5

(* uperform the Choose function *)
allow array6 = [| 1 .. 20 |]
allow array7 = Array.choose (fun elem -> if elem % 3 = 0 then
                                             Some(float (elem))
                                          else
                                             None) array6
printfn "Array with Chosen elements:"
printfn "%A" array7

(*uperform the Collect function *)
allow array8 = [| 2 .. 5 |]
allow array9 = Array.collect (fun elem -> [| 0 .. elem - 1 |]) array8
printfn "Array with collected elements:"
printfn "%A" array9

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Sub Array:
[|5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19|]
Appended Array:
[|1; 2; 3; 4; 5; 6; 7; 8; 9|]
Array with Chosen elements:
[|3.0; 6.0; 9.0; 12.0; 15.0; 18.0|]
Array with collected elements:
[|0; 1; 0; 1; 2; 0; 1; 2; 3; 0; 1; 2; 3; 4|]

Searching Arrays

The Array.find function conaspectrs a Boolean function and returns the preliminary element for which the function returns true, else raises a KeyNotFoundException.

The Array.findIndex function works similarly except tmind wear it returns the index of the element instead of the element it iself.

The folloearng example demonstrates this.

Microsmooth provides this interesting program example, which finds the preliminary element in the range of a given numend up beingr tmind wear is both a perfect square as well as a perfect cuend up being −

allow array1 = [| 2 .. 100 |]
allow delta = 1.0e-10
allow isPerfectSquare (x:int) =
   allow y = sqrt (float x)
   abs(y - round y) < delta

allow isPerfectCuend up being (x:int) =
   allow y = System.Math.Pow(float x, 1.0/3.0)
   abs(y - round y) < delta

allow element = Array.find (fun elem -> isPerfectSquare elem && isPerfectCuend up being elem) array1

allow index = Array.findIndex (fun elem -> isPerfectSquare elem && isPerfectCuend up being elem) array1

printfn "The preliminary element tmind wear is both a square and a cuend up being is %d and it is index is %d." element index

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

The preliminary element tmind wear is both a square and a cuend up being is 64 and it is index is 62.

F# – Mutable Lists

The List<'T> course represents a strongly typed list of objects tmind wear can end up being accessed by index.

It is a mutable counterpart of the List course. It is similar to arrays, as it can end up being accessed by an index, however, unlike arrays, lists can end up being redimensiond. Therefore you need not specify a dimension during declaration.

Creating a Mutable List

Lists are produced uperform the new keyword and calling the list's constructor. The folloearng example demonstrates this −

(* Creating a List *)
open System.Collections.Generic

allow booksList = new List<string>()
booksList.Add("Gone with the Wind")
booksList.Add("Atlas Shrugged")
booksList.Add("Fountainmind")
booksList.Add("Thornbirds")
booksList.Add("Reend up beingcca")
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 folloearng away correct now presently thereplace −

0: Gone with the Wind
1: Atlas Shrugged
2: Fountainmind
3: Thornbirds
4: Reend up beingcca
5: Narnia

The List(T) Clbum

The List(T) course represents a strongly typed list of objects tmind wear can end up being accessed by index. It provide methods to oceanrch, sort, and manipulate lists.

The folloearng tables provide the propertie ups, constructors and the methods of the List(T) course −

Propertie ups

Property Description
Capacity Gets or sets the comprehensive numend up beingr of elements the internal data structure can hold withaway correct now presently there resizing.
Count Gets the numend up beingr 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) course tmind wear is empty and has the default preliminary capacity.
List(T)(IEnumerable(T)) Initializes a new instance of the List(T) course tmind wear contains elements copied from the specified collection and has sufficient capacity to accommodate the numend up beingr of elements copied.
List(T)(Int32) Initializes a new instance of the List(T) course tmind wear is empty and has the specified preliminary 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 uperform 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 uperform 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 uperform 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(TOutplace) Converts the elements in the current List(T) to an additional 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 end up beingginning 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 tmind wear go with up the conditions defined by the specified preddish-coloureddishicate.
Finalize Allows an object to consider to free resources and perform other thoroughly cleanup operations end up beingfore it is reclaimed by garbage collection (Inherited from Object).
Find Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the preliminary occurrence wislim the entire List(T).
FindAll Retrieves all the elements tmind wear go with up the conditions defined by the specified preddish-coloureddishicate.
FindIndex(Preddish-coloureddishicate(T)) Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the zero-based index of the preliminary occurrence wislim the entire List(T).
FindIndex(Int32, Preddish-coloureddishicate(T)) Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the zero-based index of the preliminary occurrence wislim the range of elements in the List(T) tmind wear extends from the specified index to the final element.
FindIndex(Int32, Int32, Preddish-coloureddishicate(T)) Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the zero-based index of the preliminary occurrence wislim the range of elements in the List(T) tmind wear starts at the specified index and contains the specified numend up beingr of elements.
FindLast Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the final occurrence wislim the entire List(T).
FindLastIndex(Preddish-coloureddishicate(T)) Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the zero-based index of the final occurrence wislim the entire List(T).
FindLastIndex(Int32, Preddish-coloureddishicate(T)) Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the zero-based index of the final occurrence wislim the range of elements in the List(T) tmind wear extends from the preliminary element to the specified index.
FindLastIndex(Int32, Int32, Preddish-coloureddishicate(T)) Searches for an element tmind wear go with upes the conditions defined by the specified preddish-coloureddishicate, and returns the zero-based index of the final occurrence wislim the range of elements in the List(T) tmind wear contains the specified numend up beingr of elements and ends at the specified index.
ForEach Performs the specified actionionion on each element of the List(T).
GetEnumerator Returns an enumerator tmind wear iterates through the List(T).
GetHashCode Serves as the default hash function. (Inherited from Object.)
GetRange Creates a shenable 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 preliminary occurrence wislim the entire List(T).
IndexOf(T, Int32) Searches for the specified object and returns the zero-based index of the preliminary occurrence wislim the range of elements in the List(T) tmind wear extends from the specified index to the final element.
IndexOf(T, Int32, Int32) Searches for the specified object and returns the zero-based index of the preliminary occurrence wislim the range of elements in the List(T) tmind wear starts at the specified index and contains the specified numend up beingr of elements.
Insert Inserts an element into the List(T) at the specified index.
InsertRange Inserts the elements of a collection into the List(T) at the specified index.
LastIndexOf(T) Searches for the specified object and returns the zero-based index of the final occurrence wislim the entire List(T).
LastIndexOf(T, Int32) Searches for the specified object and returns the zero-based index of the final occurrence wislim the range of elements in the List(T) tmind wear extends from the preliminary element to the specified index.
LastIndexOf(T, Int32, Int32) Searches for the specified object and returns the zero-based index of the final occurrence wislim the range of elements in the List(T) tmind wear contains the specified numend up beingr of elements and ends at the specified index.
Memend up beingrwiseCperformle Creates a shenable copy of the current Object. (Inherited from Object.)
Remove Removes the preliminary occurrence of a specific object from the List(T).
RemoveAll Removes all the elements tmind wear go with up the conditions defined by the specified preddish-coloureddishicate.
RemoveAt Removes the element at the specified index of the List(T).
RemoveRange Removes a range of elements from the List(T).
Reverse() Reverses the order of the elements in the entire List(T).
Reverse(Int32, Int32) Reverses the order of the elements in the specified range.
Sort() Sorts the elements in the entire List(T) uperform the default comparer.
Sort(Comparison(T)) Sorts the elements in the entire List(T) uperform the specified System. Comparison(T).
Sort(IComparer(T)) Sorts the elements in the entire List(T) uperform the specified comparer.
Sort(Int32, Int32, IComparer(T)) Sorts the elements in a range of elements in List(T) uperform the specified comparer.
ToArray Copies the elements of the List(T) to a new array.
ToString Returns a string tmind wear represents the current object. (Inherited from Object.)
TrimExcess Sets the capacity to the actionionual numend up beingr of elements in the List(T), if tmind wear numend up beingr is less than a threshold value.
TrueForAll Determines whether every element in the List(T) go with upes the conditions defined by the specified preddish-coloureddishicate.

Example

(* Creating a List *)
open System.Collections.Generic

allow booksList = new List<string>()
booksList.Add("Gone with the Wind")
booksList.Add("Atlas Shrugged")
booksList.Add("Fountainmind")
booksList.Add("Thornbirds")
booksList.Add("Reend up beingcca")
booksList.Add("Narnia")

printfn"Total %d books" booksList.Count
booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])
booksList.Insert(2, "Roots")

printfn("after inserting at index 2")
printfn"Total %d books" booksList.Count

booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])
booksList.RemoveAt(3)

printfn("after removing from index 3")
printfn"Total %d books" booksList.Count

booksList |> Seq.iteri (fun index item -> printfn "%i: %s" index booksList.[index])

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Total 6 books
0: Gone with the Wind
1: Atlas Shrugged
2: Fountainmind
3: Thornbirds
4: Reend up beingcca
5: Narnia
after inserting at index 2
Total 7 books
0: Gone with the Wind
1: Atlas Shrugged
2: Roots
3: Fountainmind
4: Thornbirds
5: Reend up beingcca
6: Narnia
after removing from index 3
Total 6 books
0: Gone with the Wind
1: Atlas Shrugged
2: Roots
3: Thornbirds
4: Reend up beingcca
5: Narnia

F# – Mutable Dictionary

The Dictionary<'TKey, 'TValue> course is the mutable analog of the F# chart data structure and contains many kind of of the exaction same functions.

Recapitulating from the Map chapter in F#, a chart is a special kind of set tmind wear bumociates the values with key.

Creating of a Mutable Dictionary

Mutable dictionaries are produced uperform the new keyword and calling the list's constructor. The folloearng example demonstrates this −

open System.Collections.Generic
allow 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 - college students: %A" dict

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Dictionary - college students: seq
[[1501, Zara Ali]; [1502, Rishita Gupta]; [1503, Robin Sahoo];
[1504, Gillian Megan]]

The Dictionary(TKey,TValue) Clbum

The Dictionary(TKey, TValue) Clbum represents a collection of keys and values.

The folloearng tables provide the propertie ups, constructors and the methods of the List(T) course −

Propertie ups

Property Description
Comparer Gets the IEqualityComparer(T) tmind wear is used to determine equality of keys for the dictionary.
Count Gets the numend up beingr of key/value pairs contained in the Dictionary(TKey, TValue).
Item Gets or sets the value bumociated 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) course tmind wear is empty, has the default preliminary 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) course tmind wear 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) course tmind wear is empty, has the default preliminary capacity, and uses the specified IEqualityComparer(T).
Dictionary(TKey, TValue)(Int32) Initializes a new instance of the Dictionary(TKey, TValue) course tmind wear is empty, has the specified preliminary 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) course tmind wear 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) course tmind wear is empty, has the specified preliminary capacity, and uses the specified IEqualityComparer(T).
Dictionary(TKey, TValue)(SerializationInfo, StreamingContext) Initializes a new instance of the ictionary(TKey, TValue) course 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 consider to free resources and perform other thoroughly cleanup operations end up beingfore it is reclaimed by garbage collection. (Inherited from Object.)
GetEnumerator Returns an enumerator tmind wear 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.)
Memend up beingrwiseCperformle Creates a shenable copy of the current Object. (Inherited from Object.)
OnDeserialization Implements the System.Runtime.Serialization.ISerializable interface and raises the deserialization actionionuallyt when the deserialization is comprehensive.
Remove Removes the value with the specified key from the Dictionary(TKey, TValue).
ToString Returns a string tmind wear represents the current object. (Inherited from Object.)
TryGetValue Gets the value bumociated with the specified key.

Example

open System.Collections.Generic
allow 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 - college students: %A" dict
printfn "Total Numend up beingr 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 folloearng away correct now presently thereplace −

Dictionary - college students: seq
[[1501, Zara Ali]; [1502, Rishita Gupta]; [1503, Robin Sahoo];
[1504, Gillian Megan]]
Total Numend up beingr of Students: 4
The keys: seq ["1501"; "1502"; "1503"; "1504"]
The Values: seq ["Zara Ali"; "Rishita Gupta"; "Robin Sahoo"; "Gillian Megan"]

F# – Basic IO

Basic Inplace Outplace includes −

  • Reading from and writing into console.
  • Reading from and writing into file.

Core.Printf Module

We have used the printf and the printfn functions for writing into the console. In this section, we will look into the details of the Printf module of F#.

Apart from the above functions, the Core.Printf module of F# has various other methods for printing and formatting uperform % markers as placeholders. The folloearng table shows the methods with short description −

Value Description
bprintf : StringBuilder → BuilderFormat<'T> → 'T Prints to a StringBuilder.
eprintf : TextWriterFormat<'T> → 'T Prints formatted away correct now presently thereplace to stderr.
eprintfn : TextWriterFormat<'T> → 'T Prints formatted away correct now presently thereplace to stderr, adding a newcollection.
failwithf : StringFormat<'T,'Result> → 'T Prints to a string buffer and raises an exception with the given result.
fprintf : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer.
fprintfn : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer, adding a newcollection.
kbprintf : (device → 'Result) → StringBuilder → BuilderFormat<'T,'Result> → 'T Like bprintf, but calls the specified function to generate the result.
kfprintf : (device → 'Result) → TextWriter → TextWriterFormat<'T,'Result> → 'T Like fprintf, but calls the specified function to generate the result.
kprintf : (string → 'Result) → StringFormat<'T,'Result> → 'T Like printf, but calls the specified function to generate the result. For example, these allow the printing force a flush after all away correct now presently thereplace has end up beingen entereddish-coloureddish onto the channel, but not end up beingfore.
ksprintf : (string → 'Result) → StringFormat<'T,'Result> → 'T Like sprintf, but calls the specified function to generate the result.
printf : TextWriterFormat<'T> → 'T Prints formatted away correct now presently thereplace to stdaway correct now presently there.
printfn : TextWriterFormat<'T> → 'T Prints formatted away correct now presently thereplace to stdaway correct now presently there, adding a newcollection.
sprintf : StringFormat<'T> → 'T Prints to a string by uperform an internal string buffer and returns the result as a string.

Format Specifications

Format specifications are used for formatting the inplace or away correct now presently thereplace, according to the programmers’ need.

These are strings with % markers indicating format placeholders.

The syntax of a Format placeholders is −

%[flags][width][.precision][type]

The type is interpreted as −

Type Description
%b Formats a bool, formatted as true or false.
%c Formats a charactionioner.
%s Formats a string, formatted as it is contents, withaway correct now presently there interpreting any kind of escape charactionioners.
%d, %i Formats any kind of easy integer type formatted as a decimal integer, signed if the easy integer type is signed.
%u Formats any kind of easy integer type formatted as an unsigned decimal integer.
%x Formats any kind of easy integer type formatted as an unsigned hexadecimal integer, uperform lowercase allowters a through f.
%X Formats any kind of easy integer type formatted as an unsigned hexadecimal integer, uperform uppercase allowters A through F.
%o Formats any kind of easy integer type formatted as an unsigned octal integer.
%e, %E, %f, %F, %g, %G Formats any kind of easy floating stage type (float, float32) formatted uperform a C-style floating stage format specifications.
%e, %E Formats a signed value having the form [-]d.dddde[sign]ddd where d is a performle decimal digit, dddd is one or more decimal digit is, ddd is exactionionly three decimal digit is, and sign is + or -.
%f Formats a signed value having the form [-]dddd.dddd, where dddd is one or more decimal digit is. The numend up beingr of digit is end up beingfore the decimal stage depends on the magnitude of the numend up beingr, and the numend up beingr of digit is after the decimal stage depends on the requested precision.
%g, %G Formats a signed value printed in f or e format, whichever is more compactionion for the given value and precision.
%M Formats a Decimal value.
%O Formats any kind of value, printed by containering the object and uperform it is ToString method.
%A, %+A Formats any kind of value, printed with the default layaway correct now presently there settings. Use %+A to print the structure of discriminated unions with internal and private representations.
%a

A general format specifier, requires 2 arguments. The preliminary argument is a function which accepts 2 arguments: preliminary, a context parameter of the appropriate type for the given formatting function (for example, a TextWriter), and second, a value to print and which either away correct now presently thereplaces or returns appropriate text.

The second argument is the particular value to print.

%t A general format specifier, requires one argument: a function which accepts a context parameter of the appropriate type for the given formatting function (aTextWriter) and which either away correct now presently thereplaces or returns appropriate text. Basic integer types are byte, sbyte, int16, uint16, int32, uint32, int64, uint64, nativeint, and unativeint. Basic floating stage types are float and float32.

The width is an optional parameter. It is an integer tmind wear indicates the minimal width of the result. For example, %5d prints an integer with at minimumernern spaces of 5 charactionioners.

Valid flags are descriend up beingd in the folloearng table −

Value Description
0 Specifies to add zeros instead of spaces to make up the requireddish-coloureddish width.
Specifies to left-justify the result wislim the width specified.
+ Specifies to add a + charactionioner if the numend up beingr is positive (to go with up a – sign for negative numend up beingrs).
' ' (space) Specifies to add an extra space if the numend up beingr is positive (to go with up a – sign for negative numend up beingrs).
# Invalid.

Example

printf "Hello "
printf "World"
printfn ""
printfn "Hello "
printfn "World"
printf "Hi, I'm %s and I'm a %s" "Rohit" "Medical Student"

printfn "d: %f" 212.098f
printfn "e: %f" 504.768f

printfn "x: %g" 212.098f
printfn "y: %g" 504.768f

printfn "x: %e" 212.098f
printfn "y: %e" 504.768f
printfn "True: %b" true

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hello World
Hello
World
Hi, I'm Rohit and I'm a Medical Studentd: 212.098000
e: 504.768000
x: 212.098
y: 504.768
x: 2.120980e+002
y: 5.047680e+002
True: true

The Console Clbum

This course is a part of the .NET framework. It represents the standard inplace, away correct now presently thereplace, and error streams for console applications.

It provides various methods for reading from and writing into the console. The folloearng table shows the methods −

Method Description
Beep() Plays the sound of a end up beingep through the console speaker.
Beep(Int32, Int32) Plays the sound of a end up beingep of a specified frequency and duration through the console speaker.
Clear Clears the console buffer and corresponding console earndow of display information.
MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) Copies a specified source area of the screen buffer to a specified destination area.
MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor) Copies a specified source area of the screen buffer to a specified destination area.
OpenStandardError() Acquires the standard error stream.
OpenStandardError(Int32) Acquires the standard error stream, which is set to a specified buffer dimension.
OpenStandardInplace() Acquires the standard inplace stream.
OpenStandardInplace(Int32) Acquires the standard inplace stream, which is set to a specified buffer dimension.
OpenStandardOutplace() Acquires the standard away correct now presently thereplace stream.
OpenStandardOutplace(Int32) Acquires the standard away correct now presently thereplace stream, which is set to a specified buffer dimension.
Read Reads the next charactionioner from the standard inplace stream.
ReadKey() Obtains the next charactionioner or function key pressed by the user. The pressed key is displayed in the console earndow.
ReadKey(Boolean) Obtains the next charactionioner or function key pressed by the user. The pressed key is optionally displayed in the console earndow.
ReadLine Reads the next collection of charactionioners from the standard inplace stream.
ResetColor Sets the foreground and background console colours to their particular defaults.
SetBufferSize Sets the height and width of the screen buffer area to the specified values.
SetCursorPosition Sets the position of the cursor.
SetError Sets the Error real estate to the specified TextWriter object.
SetIn Sets the In real estate to the specified TextReader object.
SetOut Sets the Out real estate to the specified TextWriter object.
SetWindowPosition Sets the position of the console earndow relative to the screen buffer.
SetWindowSize Sets the height and width of the console earndow to the specified values.
Write(Boolean) Writes the text representation of the specified Boolean value to the standard away correct now presently thereplace stream.
Write(Char) Writes the specified Unicode charactionioner value to the standard away correct now presently thereplace stream.
Write(Char[]) Writes the specified array of Unicode charactionioners to the standard away correct now presently thereplace stream.
Write(Decimal) Writes the text representation of the specified Decimal value to the standard away correct now presently thereplace stream.
Write(Double) Writes the text representation of the specified double-precision floating-stage value to the standard away correct now presently thereplace stream.
Write(Int32) Writes the text representation of the specified 32-bit signed integer value to the standard away correct now presently thereplace stream.
Write(Int64) Writes the text representation of the specified 64-bit signed integer value to the standard away correct now presently thereplace stream.
Write(Object) Writes the text representation of the specified object to the standard away correct now presently thereplace stream.
Write(Single) Writes the text representation of the specified performle-precision floating-stage value to the standard away correct now presently thereplace stream.
Write(String) Writes the specified string value to the standard away correct now presently thereplace stream.
Write(UInt32) Writes the text representation of the specified 32-bit unsigned integer value to the standard away correct now presently thereplace stream.
Write(UInt64) Writes the text representation of the specified 64-bit unsigned integer value to the standard away correct now presently thereplace stream.
Write(String, Object) Writes the text representation of the specified object to the standard away correct now presently thereplace stream uperform the specified format information.
Write(String, Object[]) Writes the text representation of the specified array of objects to the standard away correct now presently thereplace stream uperform the specified format information.
Write(Char[], Int32, Int32) Writes the specified subarray of Unicode charactionioners to the standard away correct now presently thereplace stream.
Write(String, Object, Object) Writes the text representation of the specified objects to the standard away correct now presently thereplace stream uperform the specified format information.
Write(String, Object, Object, Object) Writes the text representation of the specified objects to the standard away correct now presently thereplace stream uperform the specified format information.
Write(String, Object, Object, Object, Object) Writes the text representation of the specified objects and variable-dimension parameter list to the standard away correct now presently thereplace stream uperform the specified format information.
WriteLine() Writes the current collection terminator to the standard away correct now presently thereplace stream.
WriteLine(Boolean) Writes the text representation of the specified Boolean value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Char) Writes the specified Unicode charactionioner, followed by the current collection terminator, value to the standard away correct now presently thereplace stream.
WriteLine(Char[]) Writes the specified array of Unicode charactionioners, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Decimal) Writes the text representation of the specified Decimal value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Double) Writes the text representation of the specified double-precision floating-stage value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Int32) Writes the text representation of the specified 32-bit signed integer value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Int64) Writes the text representation of the specified 64-bit signed integer value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Object) Writes the text representation of the specified object, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(Single) Writes the text representation of the specified performle-precision floating-stage value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(String) Writes the specified string value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(UInt32) Writes the text representation of the specified 32-bit unsigned integer value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(UInt64) Writes the text representation of the specified 64-bit unsigned integer value, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(String, Object) Writes the text representation of the specified object, followed by the current collection terminator, to the standard away correct now presently thereplace stream uperform the specified format information.
WriteLine(String, Object[]) Writes the text representation of the specified array of objects, followed by the current collection terminator, to the standard away correct now presently thereplace stream uperform the specified format information.
WriteLine(Char[], Int32, Int32) Writes the specified subarray of Unicode charactionioners, followed by the current collection terminator, to the standard away correct now presently thereplace stream.
WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current collection terminator, to the standard away correct now presently thereplace stream uperform the specified format information.
WriteLine(String, Object, Object, Object) Writes the text representation of the specified objects, followed by the current collection terminator, to the standard away correct now presently thereplace stream uperform the specified format information.
WriteLine(String, Object, Object, Object, Object) Writes the text representation of the specified objects and variable-dimension parameter list, followed by the current collection terminator, to the standard away correct now presently thereplace stream uperform the specified format information.

The folloearng example demonstrates reading from console and writing into it −

Example

open System
allow main() =
   Console.Write("Wmind wear's your own name? ")
   allow name = Console.ReadLine()
   Console.Write("Hello, {0}n", name)
   Console.WriteLine(System.String.Format("Big Greetings from {0} and {1}", "TutorialsPoint", "Absoulte Clbumes"))
   Console.WriteLine(System.String.Format("|{0:yyyy-MMM-dd}|", System.DateTime.Now))
main()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Wmind wear's your own name? Kabir
Hello, Kabir
Big Greetings from TutorialsPoint and Absoulte Clbumes
|2015-Jan-05|

The System.IO Namespace

The System.IO namespace contains a variety of useful coursees for performing easy I/O.

It contains types or coursees tmind wear enable reading and writing to files and data streams and types tmind wear provide easy file and immediateory supslot.

Clbumes useful for worruler with the file system −

  • The System.IO.File course is used for creating, appending, and deallowing files.
  • System.IO.Directory course is used for creating, moving, and deallowing immediateories.
  • System.IO.Path course performs operations on strings, which represent file paths.
  • System.IO.FileSystemWatcher course enables users to listen to a immediateory for alters.

Clbumes useful for worruler with the streams (sequence of bytes) −

  • System.IO.StreamReader course is used to read charactionioners from a stream.
  • System.IO.StreamWriter course is used to write charactionioners to a stream.
  • System.IO.MemoryStream course produces an in-memory stream of bytes.

The folloearng table shows all the coursees provided in the namespace alengthy with a short description −

Clbum Description
BinaryReader Reads primitive data types as binary values in a specific encoding.
BinaryWriter Writes primitive types in binary to a stream and supslots writing strings in a specific encoding.
Buffereddish-coloureddishStream Adds a buffering layer to read and write operations on an additional stream.
Directory Exposes static methods for creating, moving, and enumerating through immediateories and subimmediateories.
DirectoryInfo Exposes instance methods for creating, moving, and enumerating through immediateories and subimmediateories.
DirectoryNotFoundException The exception tmind wear is thrown when part of a file or immediateory cannot end up being found.
DriveInfo Provides access to information on a drive.
DriveNotFoundException The exception tmind wear is thrown when thinking to access a drive or share tmind wear is not available.
EndOfStreamException The exception tmind wear is thrown when reading is attempted past the end of a stream.
ErrorEventArgs Provides data for the FileSystemWatcher.Error actionionuallyt.
File Provides static methods for the creation, copying, deallowion, moving, and opening of a performle file, and aids in the creation of FileStream objects.
FileFormatException The exception tmind wear is thrown when an inplace file or a data stream tmind wear is meant to conform to a specific file format specification is malformed.
FileInfo Provides propertie ups and instance methods for the creation, copying, deallowion, moving, and opening of files, and aids in the creation of FileStream objects.
FileLoadException The exception tmind wear is thrown when a managed bumembly is found but cannot end up being loaded.
FileNotFoundException The exception tmind wear is thrown when an attempt to access a file tmind wear does not exist on disk fails.
FileStream Exposes a Stream around a file, supsloting both synchronous and asynchronous read and write operations.
FileSystemEventArgs Provides data for the immediateory actionionuallyts − Changed, Created, Deallowed.
FileSystemInfo Provides the base course for both FileInfo and DirectoryInfo objects.
FileSystemWatcher Listens to the file system alter notifications and raises actionionuallyts when a immediateory, or file in a immediateory, alters.
InternalBufferOverflowException The exception thrown when the internal buffer overflows.
InvalidDataException The exception tmind wear is thrown when a data stream is in an invalid format.
IODescriptionAttribute Sets the description visual styleers can display when referencing an actionionuallyt, extender, or real estate.
IOException The exception tmind wear is thrown when an I/O error occurs.
MemoryStream Creates a stream in whose bacruler store is memory.
Path Performs operations on String instances tmind wear contain file or immediateory path information. These operations are performed in a combination-platform manner.
PathTooLongException The exception tmind wear is thrown when a path or file name is lengthyer than the system-defined maximum dimension.
PipeException Thrown when an error occurs wislim a named pipe.
RenamedEventArgs Provides data for the Renamed actionionuallyt.
Stream Provides a generic watch of a sequence of bytes. This is an abstractionion course.
StreamReader Implements a TextReader tmind wear reads charactionioners from a byte stream in a particular encoding.
StreamWriter Implements a TextWriter for writing charactionioners to a stream in a particular encoding. To browse the .NET Framework source code for this type, see the Reference Source.
StringReader Implements a TextReader tmind wear reads from a string.
StringWriter Implements a TextWriter for writing information to a string. The information is storeddish-coloureddish in an underlying StringBuilder.
TextReader Represents a reader tmind wear can read a sequential series of charactionioners.
TextWriter Represents a writer tmind wear can write a sequential series of charactionioners. This course is abstractionion.
UnmanagedMemoryAccessor Provides random access to unmanaged blocks of memory from managed code.
UnmanagedMemoryStream Provides access to unmanaged blocks of memory from managed code.
WindowsRuntimeStorageExtensions Contains extension methods for the IStorageFile and IStorageFolder interfaces in the Windows Runtime when produceing Windows Store apps.
WindowsRuntimeStreamExtensions Contains extension methods for converting end up beingtween streams in the Windows Runtime and managed streams in the .NET for Windows Store apps.

Example

The folloearng example produces a file calintroduced test.txt, writes a message correct now presently there, reads the text from the file and prints it on the console.

Note − The amount of code needed to do this is surpriperformly less!

open System.IO // Name spaces can end up being opened only as modules
File.WriteAllText("test.txt", "Hello Theren Welcome to:n Tutorials Point")
allow msg = File.ReadAllText("test.txt")
printfn "%s" msg

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hello There
Welcome to:
Tutorials Point

F# – Generics

Generics enable you to delay the specification of the data type of programming elements in a course or a method, until it is actionionually used in the program. In other words, generics enable you to write a course or method tmind wear can work with any kind of data type.

You write the specifications for the course or the method, with substitute parameters for data types. When the compiler encounters a constructor for the course or a function call for the method, it generates code to handle the specific data type.

In F#, function values, methods, propertie ups, and aggregate types such as coursees, records, and discriminated unions can end up being generic.

Generic constructs contain at minimumernern one type parameter. Generic functions and types enable you to write code tmind wear works with a variety of types withaway correct now presently there repeating the code for each type.

Syntax

Syntax for writing a generic construct is as follows −

// Explicitly generic function.
allow function-name<type-parameters> parameter-list =
   function-body

// Explicitly generic method.
[ static ] memend up beingr object-identifer.method-name<type-parameters> parameter-list [ return-type ] =
   method-body

// Explicitly generic course, record, interface, structure,
// or discriminated union.
type type-name<type-parameters> type-definition

Examples

(* Generic Function *)
allow printFunc x y =
   printfn "%A, %A" x y

printFunc<float> 10.0 20.0

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

10.0, 20.0

You can also make a function generic by uperform the performle quotation mark syntax −

(* Generic Function *)
allow printFunction (x: 'a) (y: 'a) =
   printfn "%A %A" x y

printFunction 10.0 20.0

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

10.0 20.0

Please note tmind wear when you use generic functions or methods, you may not have to specify the type arguments. However, in case of an ambiguity, you can provide type arguments in angle brackets as we did in the preliminary example.

If you have more than one type, then you separate multiple type arguments with commas.

Generic Clbum

Like generic functions, you can also write generic coursees. The folloearng example demonstrates this −

type genericClbum (x: 'a) =
   do printfn "%A" x

allow gr = new genericClbum<string>("zara")
allow gs = genericClbum( seq { for i in 1 .. 10 -> (i, i*i) } )

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

"zara"
seq [(1, 1); (2, 4); (3, 9); (4, 16); ...]

F# – Delegates

A delegate is a reference type variable tmind wear holds the reference to a method. The reference can end up being alterd at runtime. F# delegates are similar to stageers to functions, in C or C++.

Declaring Delegates

Delegate declaration determines the methods tmind wear can end up being referenced by the delegate. A delegate can refer to a method, which have the exaction same sigcharactioner as tmind wear of the delegate.

Syntax for delegate declaration is −

type delegate-typename = delegate of type1 -> type2

For example, conaspectr 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 end up being used to reference any kind of method tmind wear has 2 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 end up being attached to function values, and static or instance methods.

  • F# function values can end up being moveed immediately as arguments to delegate constructors.

  • For a static method the delegate is calintroduced by uperform the name of the course 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 end up being moveed as function values by referencing the Invoke method name withaway correct now presently there the mother or fatherheses.

The folloearng example demonstrates the concept −

Example

type Mycourse() =
   static memend up beingr add(a : int, b : int) =
      a + b
   static memend up beingr sub (a : int) (b : int) =
      a - b
   memend up beingr x.Add(a : int, b : int) =
      a + b
   memend up beingr 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

allow InvokeDelegate1 (dlg : Delegate1) (a : int) (b: int) =
   dlg.Invoke(a, b)
allow InvokeDelegate2 (dlg : Delegate2) (a : int) (b: int) =
   dlg.Invoke(a, b)

// For static methods, use the course name, the dot operator, and the
// name of the static method.
allow del1 : Delegate1 = new Delegate1( Mycourse.add )
allow del2 : Delegate2 = new Delegate2( Mycourse.sub )

allow mc = Mycourse()
// For instance methods, use the instance value name, the dot operator, and the instance method name.

allow del3 : Delegate1 = new Delegate1( mc.Add )
allow 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 folloearng away correct now presently thereplace −

400 + 200 = 600
400 - 200 = 200
400 + 200 = 600
400 - 200 = 200
100 + 45 = 145
100 - 45 = 55
100 + 45 = 145
100 - 45 = 55

F# – Enumerations

An enumeration is a set of named integer constants.

In F#, enumerations, also known as enums, are integral types where laend up beingls are bumigned to a subset of the values. You can use all of them in place of literals to make code more readable and maintainable.

Declaring Enumerations

The general syntax for declaring an enumeration is −

type enum-name =
   | value1 = integer-literal1
   | value2 = integer-literal2
...

The folloearng example demonstrates the use of enumerations −

Example

// Declaration of an enumeration.
type Days =
   | Sun = 0
   | Mon = 1
   | Tues = 2
   | Wed = 3
   | Thurs = 4
   | Fri = 5
   | Sat = 6

// Use of an enumeration.
allow weekend1 : Days = Days.Sat
allow weekend2 : Days = Days.Sun
allow weekDay1 : Days = Days.Mon

printfn "Monday: %A" weekDay1
printfn "Saturday: %A" weekend1
printfn "Sunday: %A" weekend2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Monday: Mon
Saturday: Sat
Sunday: Sun

F# – Pattern Matching

Pattern go with uping enables you to “compare data with a logical structure or structures, decompose data into constituent parts, or extractionion information from data in various ways”.

In other terms, it provides a more flexible and powerful way of testing data against a series of conditions and performing a few complaceations based on the condition met.

Conceptually, it is like a series of if… then statements.

Syntax

In high level terms, pattern go with uping follows this syntax in F# −

go with up expr with
| pat1 - result1
| pat2 -> result2
| pat3 when expr2 -> result3
| _ -> defaultResult

Where,

  • Each | symbol defines a condition.
  • The -> symbol means "if the condition is true, return this value…".
  • The _ symbol provides the default pattern, meaning tmind wear it go with upes all other slimgs like a wildcard.

Example 1

The folloearng example, calculates the Fibonacci numend up beingrs uperform pattern go with uping syntax −

allow rec fib n =
   go with up n with
   | 0 -> 0
   | 1 -> 1
   | _ -> fib (n - 1) + fib (n - 2)
for i = 1 to 10 do
   printfn "Fibonacci %d: %d" i (fib i)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Fibonacci 1: 1
Fibonacci 2: 1
Fibonacci 3: 2
Fibonacci 4: 3
Fibonacci 5: 5
Fibonacci 6: 8
Fibonacci 7: 13
Fibonacci 8: 21
Fibonacci 9: 34
Fibonacci 10: 55

You can also chain with each other multiple conditions, which return the exaction same value. For example −

Example 2

allow printSeason month =
   go with up month with
   | "Decemend up beingr" | "January" | "February" -> printfn "Winter"
   | "March" | "April" -> printfn "Spring"
   | "May" | "June" -> printfn "Summer"
   | "July" | "August" -> printfn "Rainy"
   | "Septemend up beingr" | "Octoend up beingr" | "Novemend up beingr" -> printfn "Autumn"
   | _ -> printfn "Season depends on month!"

printSeason "February"
printSeason "April"
printSeason "Novemend up beingr"
printSeason "July"

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Winter
Spring
Autumn
Rainy

Pattern Matching Functions

F# enables you to write pattern go with uping functions uperform the function keyword −

allow getRate = function
   | "potato" -> 10.00
   | "brinjal" -> 20.50
   | "cauliflower" -> 21.00
   | "cabbage" -> 8.75
   | "carrot" -> 15.00
   | _ -> nan (* nan is a special value meaning "not a numend up beingr" *)

printfn "%g"(getRate "potato")
printfn "%g"(getRate "brinjal")
printfn "%g"(getRate "cauliflower")
printfn "%g"(getRate "cabbage")
printfn "%g"(getRate "carrot")

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

10
20.5
21
8.75
15

Adding Filters or Guards to Patterns

You can add filters, or guards, to patterns uperform the when keyword.

Example 1

allow sign = function
   | 0 -> 0
   | x when x < 0 -> -1
   | x when x > 0 -> 1

printfn "%d" (sign -20)
printfn "%d" (sign 20)
printfn "%d" (sign 0)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

-1
1
0

Example 2

allow compareInt x =
   go with up x with
   | (var1, var2) when var1 > var2 -> printfn "%d is greater than %d" var1 var2
   | (var1, var2) when var1 < var2 -> printfn "%d is less than %d" var1 var2
   | (var1, var2) -> printfn "%d equals %d" var1 var2

compareInt (11,25)
compareInt (72, 10)
compareInt (0, 0)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

11 is less than 25
72 is greater than 10
0 equals 0

Pattern Matching with Tuples

The folloearng example demonstrates the pattern go with uping with tuples −

allow greeting (name, subject) =
   go with up (name, subject) with
   | ("Zara", _) -> "Hello, Zara"
   | (name, "English") -> "Hello, " + name + " from the department of English"
   | (name, _) when subject.StartsWith("Comp") -> "Hello, " + name + " from the department of Complaceer Sc."
   | (_, "Accounts and Finance") -> "Welcome to the department of Accounts and Finance!"
   | _ -> "You are not registereddish-coloureddish into the system"

printfn "%s" (greeting ("Zara", "English"))
printfn "%s" (greeting ("Raman", "Complaceer Science"))
printfn "%s" (greeting ("Ravi", "Maall of thematics"))

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hello, Zara
Hello, Raman from the department of Complaceer Sc.
You are not registereddish-coloureddish into the system

Pattern Matching with Records

The folloearng example demonstrates pattern go with uping with records −

type Point = { x: float; y: float }
allow evaluatePoint (stage: Point) =
   go with up stage with
   | { x = 0.0; y = 0.0 } -> printfn "Point is at the origin."
   | { x = xVal; y = 0.0 } -> printfn "Point is on the x-axis. Value is %f." xVal
   | { x = 0.0; y = yVal } -> printfn "Point is on the y-axis. Value is %f." yVal
   | { x = xVal; y = yVal } -> printfn "Point is at (%f, %f)." xVal yVal

evaluatePoint { x = 0.0; y = 0.0 }
evaluatePoint { x = 10.0; y = 0.0 }
evaluatePoint { x = 0.0; y = 10.0 }
evaluatePoint { x = 10.0; y = 10.0 }

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Point is at the origin.
Point is on the x-axis. Value is 10.000000.
Point is on the y-axis. Value is 10.000000.
Point is at (10.000000, 10.000000).

F# – Exception Handling

An exception is a problem tmind wear arises during the execution of a program. An F# exception is a response to an exceptional circumstance tmind wear arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer manage from one part of a program to an additional. F# exception handling provides the folloearng constructs −

Construct Description
raise expr Raises the given exception.
failwith expr Raises the System.Exception exception.
consider expr with rules Catches expressions go with uping the pattern rules.
consider expr finally expr Execution the finally expression both when the complaceation is successful and when an exception is raised.
| 😕 ArgumentException A rule go with uping the given .NET exception type.
| 😕 ArgumentException as e A rule go with uping the given .NET exception type, binding the name e to the exception object value.
| Failure(msg) → expr A rule go with uping the given data-carrying F# exception.
| exn → expr A rule go with uping any kind of exception, binding the name exn to the exception object value.
| exn when expr → expr A rule go with uping the exception under the given condition, binding the name exn to the exception object value.

Let us start with the easy syntax of Exception Handling.

Syntax

Basic syntax for F# exception handling block is −

exception exception-type of argument-type

Where,

  • exception-type is the name of a new F# exception type.

  • argument-type represents the type of an argument tmind wear can end up being suppare locatedd when you raise an exception of this type.

  • Multiple arguments can end up being specified by uperform a tuple type for argument-type.

The consider…with expression is used for exception handling in the F# language.

Syntax for the consider … with expression is −

consider
   expression1
with
   | pattern1 -> expression2
   | pattern2 -> expression3
...

The consider…finally expression enables you to execute thoroughly clean-up code actionionually if a block of code throws an exception.

Syntax for the consider … finally expression is −

consider
   expression1
finally
   expression2

The raise function is used to indicate tmind wear an error or exceptional condition has occurreddish-coloureddish. It also captures the information abaway correct now presently there the error in an exception object.

Syntax for the raise function is −

raise (expression)

The failwith function generates an F# exception.

Syntax for the failwith function is −

failwith error-message-string

The invalidArg function generates an argument exception.

invalidArg parameter-name error-message-string

Example of Exception Handling

Example 1

The folloearng program shows the easy exception handling with a easy consider… with block −

allow divisionprog x y =
   consider
      Some (x / y)
   with
      | :? System.DivideByZeroException -> printfn "Division by zero!"; None

allow result1 = divisionprog 100 0

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Division by zero!

Example 2

F# provides an exception type for declaring exceptions. You can use an exception type immediately in the filters in a consider…with expression.

The folloearng example demonstrates this −

exception Error1 of string
// Uperform a tuple type as the argument type.
exception Error2 of string * int

allow myfunction x y =
   consider
      if x = y then raise (Error1("Equal Numend up beingr Error"))
      else raise (Error2("Error Not detected", 100))
   with
      | Error1(str) -> printfn "Error1 %s" str
      | Error2(str, i) -> printfn "Error2 %s %d" str i
myfunction 20 10
myfunction 5 5

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Error2 Error Not detected 100
Error1 Equal Numend up beingr Error

Example 3

The folloearng example demonstrates nested exception handling −

exception InnerError of string
exception OuterError of string

allow func1 x y =
   consider
      consider
         if x = y then raise (InnerError("internal error"))
         else raise (OuterError("away correct now presently thereer error"))
      with
         | InnerError(str) -> printfn "Error:%s" str
   finally
      printfn "From the finally block."

allow func2 x y =
   consider
      func1 x y
   with
      | OuterError(str) -> printfn "Error: %s" str

func2 100 150
func2 100 100
func2 100 120

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

From the finally block.
Error: away correct now presently thereer error
Error:internal error
From the finally block.
From the finally block.
Error: away correct now presently thereer error

Example 4

The folloearng function demonstrates the failwith function −

allow divisionFunc x y =
   if (y = 0) then failwith "Divisor cannot end up being zero."
   else
      x / y

allow considerdivisionFunc x y =
   consider
      divisionFunc x y
   with
      | Failure(msg) -> printfn "%s" msg; 0

allow result1 = considerdivisionFunc 100 0
allow result2 = considerdivisionFunc 100 4
printfn "%A" result1
printfn "%A" result2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Divisor cannot end up being zero.
0
25

Example 5

The invalidArg function generates an argument exception. The folloearng program demonstrates this −

allow days = [| "Sunday"; "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday" |]
allow findDay day =
   if (day > 7 || day < 1)
      then invalidArg "day" (sprintf "You have entereddish-coloureddish %d." day)
   days.[day - 1]

printfn "%s" (findDay 1)
printfn "%s" (findDay 5)
printfn "%s" (findDay 9)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Sunday
Thursday
Unhandintroduced Exception:
System.ArgumentException: You have entereddish-coloureddish 9.
…

Some other information abaway correct now presently there the file and variable cauperform error in the system will also end up being displayed, depending upon the system.

F# – Clbumes

Clbumes are types tmind wear represent objects tmind wear can have propertie ups, methods, and actionionuallyts. ‘They are used to model actionionions, processes, and any kind of conceptual entitie ups in applications.’

Syntax

Syntax for defining a course type is as follows −

// Clbum definition:
type [access-modifier] type-name [type-params] [access-modifier] ( parameter-list ) [ as identifier ] =
   [ course ]
      [ inherit base-type-name(base-constructor-args) ]
      [ allow-bindings ]
      [ do-bindings ]
      memend up beingr-list
      ...
   [ end ]

// Mutually recursive course definitions:
type [access-modifier] type-name1 ...
and [access-modifier] type-name2 ...
...

Where,

  • The type-name is any kind of valid identifier. Default access modifier for this is public.

  • The type-params descriend up beings optional generic type parameters.

  • The parameter-list descriend up beings 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 end up being used in the type definition to refer to the instance of the type.

  • The inherit keyword enables you to specify the base course for a course.

  • The allow bindings enable you to declare fields or function values local to the course.

  • The do-bindings section includes code to end up being executed upon object construction.

  • The memend up beingr-list consists of additional constructors, instance and static method declarations, interface declarations, abstractionion bindings, and real estate and actionionuallyt declarations.

  • The keywords course and end tmind wear mark the start and end of the definition are optional.

Constructor of a Clbum

The constructor is code tmind wear produces an instance of the course type.

In F#, constructors work small variously than other .Net languages. In the course definition, the arguments of the primary constructor are descriend up beingd as parameter-list.

The body of the constructor consists of the allow and do bindings.

You can add additional constructors by uperform the new keyword to add a memend up beingr −

new (argument-list) = constructor-body

The folloearng example illustrates the concept −

Example

The folloearng program produces a collection course alengthy with a constructor tmind wear calculates the dimension of the collection while an object of the course is produced −

type Line = course
   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

   memend up beingr x.Length =
      allow sqr x = x * x
      sqrt(sqr(x.X1 - x.X2) + sqr(x.Y1 - x.Y2) )
end
allow aLine = new Line(1.0, 1.0, 4.0, 5.0)

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Creating Line: {(1, 1), (4, 5)}
Length: 5

Let Bindings

The allow bindings in a course definition enable you to define private fields and private functions for F# coursees.

type Greetings(name) as gr =
   allow data = name
   do
      gr.PrintMessage()
   memend up beingr this.PrintMessage() =
      printf "Hello %sn" data
allow gtr = new Greetings("Zara")

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hello Zara

Please note the use of self-identifier gr for the Greetings course.

F# – Structures

A structure in F# is a value type data type. It helps you to make a performle variable, hold related data of various data types. The struct keyword is used for creating a structure.

Syntax

Syntax for defining a structure is as follows −

[ attributes ]
type [accessibility-modifier] type-name =
   struct
      type-definition-elements
   end
// or
[ attributes ]
[<StructAttribute>]
type [accessibility-modifier] type-name =
   type-definition-elements

There are 2 syntaxes. The preliminary syntax is the majority ofly used, end up beingcause, if you use the struct and end keywords, you can omit the StructAttribute attribute.

The structure definition elements provide −

  • Memend up beingr declarations and definitions.
  • Constructors and mutable and immutable fields.
  • Memend up beingrs and interface implementations.

Unlike coursees, structures cannot end up being inherited and cannot contain allow or do bindings. Since, structures do not have allow bindings; you must declare fields in structures by uperform the val keyword.

When you define a field and it is type uperform val keyword, you cannot preliminaryize the field value, instead they are preliminaryized to zero or null. So for a structure having an implicit constructor, the val declarations end up being annotated with the DefaultValue attribute.

Example

The folloearng program produces a collection structure alengthy with a constructor. The program calculates the dimension of a collection uperform the structure −

type Line = struct
   val X1 : float
   val Y1 : float
   val X2 : float
   val Y2 : float

   new (x1, y1, x2, y2) =
      {X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;}
end
allow calcLength(a : Line)=
   allow sqr a = a * a
   sqrt(sqr(a.X1 - a.X2) + sqr(a.Y1 - a.Y2) )

allow aLine = new Line(1.0, 1.0, 4.0, 5.0)
allow dimension = calcLength aLine
printfn "Length of the Line: %g " dimension

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Length of the Line: 5

F# – Operator Overloading

You can reddish-coloureddishefine or overload the majority of 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, enshutd in brackets. They must end up being defined as static course memend up beingrs. Like any kind of other function, an overloaded operator has a return type and a parameter list.

The folloearng example, shows a + operator on complex numend up beingrs −

//overloading + operator
static memend up beingr (+) (a : Complex, b: Complex) =
Complex(a.x + b.x, a.y + b.y)

The above function implements the addition operator (+) for a user-defined course Complex. It adds the attributes of 2 objects and returns the resultant Complex object.

Implementation of Operator Overloading

The folloearng program shows the comprehensive implementation −

//implementing a complex course with +, and - operators
//overloaded
type Complex(x: float, y : float) =
   memend up beingr this.x = x
   memend up beingr this.y = y
   //overloading + operator
   static memend up beingr (+) (a : Complex, b: Complex) =
      Complex(a.x + b.x, a.y + b.y)

   //overloading - operator
   static memend up beingr (-) (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 2 complex numend up beingrs
allow c1 = Complex(7.0, 5.0)
allow c2 = Complex(4.2, 3.1)

// addition and take awayionionion uperform the
//overloaded operators
allow c3 = c1 + c2
allow c4 = c1 - c2

//printing the complex numend up beingrs
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 folloearng away correct now presently thereplace −

7 5
4.2 3.1
11.2 8.1
2.8 1.9

F# – Inheritance

One of the the majority of imslotant concepts in object-oriented programming is tmind wear of inheritance. Inheritance enables us to define a course in terms of an additional course, which makes it easier to produce and maintain an application. This also provides an opslotdevicey to reuse the code functionality and fast implementation time.

When creating a course, instead of writing comprehensively new data memend up beingrs and memend up beingr functions, the programmer can styleate tmind wear the new course ought to inherit the memend up beingrs of an existing course. This existing course is calintroduced the base course, and the new course is referreddish-coloureddish to as the derived course.

The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, canine IS-A mammal hence canine IS-A animal as well and so on.

Base Clbum and Sub Clbum

A subcourse is derived from a base course, which is already defined. A subcourse inherit is the memend up beingrs of the base course, as well as has it is own memend up beingrs.

A subcourse is defined uperform the inherit keyword as shown end up beinglow −

type MyDerived(...) =
   inherit MyBase(...)

In F#, a course can have at the majority of one immediate base course. If you do not specify a base course by uperform the inherit keyword, the course implicitly inherit is from Object.

Please note −

  • The methods and memend up beingrs of the base course are available to users of the derived course like the immediate memend up beingrs of the derived course.

  • Let bindings and constructor parameters are private to a course and, correct now presently therefore, cannot end up being accessed from derived coursees.

  • The keyword base refers to the base course instance. It is used like the self-identifier.

Example

type Person(name) =
   memend up beingr x.Name = name
   memend up beingr x.Greet() = printfn "Hi, I'm %s" x.Name

type Student(name, college studentID : int) =
   inherit Person(name)
   allow mutable _GPA = 0.0
   memend up beingr x.StudentID = college studentID
   memend up beingr x.GPA
      with get() = _GPA
      and set value = _GPA <- value

type Teacher(name, expertise : string) =
   inherit Person(name)

   allow mutable _salary = 0.0
   memend up beingr x.Salary
      with get() = _salary
      and set value = _salary <- value
   memend up beingr x.Expertise = expertise

//uperform the subcoursees
allow p = new Person("Mohan")
allow st = new Student("Zara", 1234)
allow tr = new Teacher("Mariam", "Java")

p.Greet()
st.Greet()
tr.Greet()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hi, I'm Mohan
Hi, I'm Zara
Hi, I'm Mariam

Overriding Methods

You can override a default end up beinghavior of a base course method and implement it variously in the subcourse or the derived course.

Methods in F# are not overridable by default.

To override methods in a derived course, you have to declare your own method as overridable uperform the abstractionion and default keywords as follows −

type Person(name) =
   memend up beingr x.Name = name
   abstractionion Greet : device -> device
   default x.Greet() = printfn "Hi, I'm %s" x.Name

Now, the Greet method of the Person course can end up being overridden in derived coursees. The folloearng example demonstrates this −

Example

type Person(name) =
   memend up beingr x.Name = name
   abstractionion Greet : device -> device
   default x.Greet() = printfn "Hi, I'm %s" x.Name

type Student(name, college studentID : int) =
   inherit Person(name)

   allow mutable _GPA = 0.0

   memend up beingr x.StudentID = college studentID
   memend up beingr x.GPA
      with get() = _GPA
      and set value = _GPA <- value
   override x.Greet() = printfn "Student %s" x.Name

type Teacher(name, expertise : string) =
   inherit Person(name)
   allow mutable _salary = 0.0
   memend up beingr x.Salary
      with get() = _salary
      and set value = _salary <- value

   memend up beingr x.Expertise = expertise
   override x.Greet() = printfn "Teacher %s." x.Name

//uperform the subcoursees
allow p = new Person("Mohan")
allow st = new Student("Zara", 1234)
allow tr = new Teacher("Mariam", "Java")

//default Greet
p.Greet()

//Overriden Greet
st.Greet()
tr.Greet()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Hi, I'm Mohan
Student Zara
Teacher Mariam.

Abstractionion Clbum

At times you need to provide an incomprehensive implementation of an object, which ought to not end up being implemented in reality. Later, a few other programmer ought to produce subcoursees of the abstractionion course to a comprehensive implementation.

For example, the Person course will not end up being needed in a School Management System. However, the Student or the Teacher course will end up being needed. In such cases, you can declare the Person course as an abstractionion course.

The AbstractionionClbum attribute tells the compiler tmind wear the course has a few abstractionion memend up beingrs.

You cannot produce an instance of an abstractionion course end up beingcause the course is not comprehensivey implemented.

The folloearng example demonstrates this −

Example

[<AbstractionionClbum>]
type Person(name) =
   memend up beingr x.Name = name
   abstractionion Greet : device -> device

type Student(name, college studentID : int) =
   inherit Person(name)
   allow mutable _GPA = 0.0
   memend up beingr x.StudentID = college studentID
   memend up beingr x.GPA
      with get() = _GPA
      and set value = _GPA <- value
   override x.Greet() = printfn "Student %s" x.Name

type Teacher(name, expertise : string) =
   inherit Person(name)
   allow mutable _salary = 0.0
   memend up beingr x.Salary
      with get() = _salary
      and set value = _salary <- value
   memend up beingr x.Expertise = expertise
   override x.Greet() = printfn "Teacher %s." x.Name

allow st = new Student("Zara", 1234)
allow tr = new Teacher("Mariam", "Java")

//Overriden Greet
st.Greet()
tr.Greet()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Student Zara
Teacher Mariam.

F# – Interfaces

Interfaces provide an abstractionion way of writing up the implementation details of a course. It is a template tmind wear declares the methods the course must implement and expose publicly.

Syntax

An interface specifies the sets of related memend up beingrs tmind wear other coursees implement. It has the folloearng syntax −

// Interface declaration:
[ attributes ]
type interface-name =
   [ interface ]
      [ inherit base-interface-name ...]
      abstractionion memend up beingr1 : [ argument-types1 -> ] return-type1
      abstractionion memend up beingr2 : [ argument-types2 -> ] return-type2
      ...
   [ end ]
	
// Implementing, inaspect a course type definition:
interface interface-name with
   memend up beingr self-identifier.memend up beingr1 argument-list = method-body1
   memend up beingr self-identifier.memend up beingr2 argument-list = method-body2
// Implementing, by uperform an object expression:
[ attributes ]
allow course-name (argument-list) =
   { new interface-name with
      memend up beingr self-identifier.memend up beingr1 argument-list = method-body1
      memend up beingr self-identifier.memend up beingr2 argument-list = method-body2
      [ base-interface-definitions ]
   }
memend up beingr-list

Please note −

  • In an interface declaration the memend up beingrs are not implemented.

  • The memend up beingrs are abstractionion, declareddish-coloureddish by the abstractionion keyword. However you may provide a default implementation uperform the default keyword.

  • You can implement interfaces either by uperform object expressions or by uperform course types.

  • In course or object implementation, you need to provide method boexpires for abstractionion methods of the interface.

  • The keywords interface and end, which mark the start and end of the definition, are optional.

For example,

type IPerson =
   abstractionion Name : string
   abstractionion Enter : device -> device
   abstractionion Leave : device -> device

Calling Interface Methods

Interface methods are calintroduced through the interface, not through the instance of the course or type implementing interface. To call an interface method, you up cast to the interface type by uperform the :> operator (upcast operator).

For example,

(s :> IPerson).Enter()
(s :> IPerson).Leave()

The folloearng example illustrates the concept −

Example

type IPerson =
   abstractionion Name : string
   abstractionion Enter : device -> device
   abstractionion Leave : device -> device

type Student(name : string, id : int) =
   memend up beingr this.ID = id
   interface IPerson with
      memend up beingr this.Name = name
      memend up beingr this.Enter() = printfn "Student entering premises!"
      memend up beingr this.Leave() = printfn "Student leaving premises!"

type StuffMemend up beingr(name : string, id : int, salary : float) =
   allow mutable _salary = salary

   memend up beingr this.Salary
      with get() = _salary
      and set(value) = _salary <- value

   interface IPerson with
      memend up beingr this.Name = name
      memend up beingr this.Enter() = printfn "Stuff memend up beingr entering premises!"
      memend up beingr this.Leave() = printfn "Stuff memend up beingr leaving premises!"

allow s = new Student("Zara", 1234)
allow st = new StuffMemend up beingr("Rohit", 34, 50000.0)

(s :> IPerson).Enter()
(s :> IPerson).Leave()
(st :> IPerson).Enter()
(st :> IPerson).Leave()

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Student entering premises!
Student leaving premises!
Stuff memend up beingr entering premises!
Stuff memend up beingr leaving premises!

Interface Inheritance

Interfaces can inherit from one or more base interfaces.

The folloearng example shows the concept −

type Interface1 =
   abstractionion memend up beingr doubleIt: int -> int

type Interface2 =
   abstractionion memend up beingr tripleIt: int -> int

type Interface3 =
   inherit Interface1
   inherit Interface2
   abstractionion memend up beingr printIt: int -> string

type multipare locatedrClbum() =
   interface Interface3 with
      memend up beingr this.doubleIt(a) = 2 * a
      memend up beingr this.tripleIt(a) = 3 * a
      memend up beingr this.printIt(a) = a.ToString()

allow ml = multipare locatedrClbum()
printfn "%d" ((ml:>Interface3).doubleIt(5))
printfn "%d" ((ml:>Interface3).tripleIt(5))
printfn "%s" ((ml:>Interface3).printIt(5))

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

10
15
5

F# – Events

Events enable coursees to send and receive messages end up beingtween one an additional.

In GUI, actionionuallyts are user actionionions like key press, clicks, mouse movements, etc., or a few occurrence like system generated notifications. Applications need to respond to actionionuallyts when they occur. For example, interrupts. Events are used for inter-process communication.

Objects communicate with one an additional through synchronous message moveing.

Events are attached to other functions; objects register callback functions to an actionionuallyt, and these callbacks are executed when (and if) the actionionuallyt is triggereddish-coloureddish by a few object.

The Event Clbum and Event Module

The Control.Event<'T> Clbum helps in creating an observable object or actionionuallyt.

It has the folloearng instance memend up beingrs to work with the actionionuallyts −

Memend up beingr Description
Publish Publishes an observation as a preliminary course value.
Trigger Triggers an observation uperform the given parameters.

The Control.Event Module provides functions for managing actionionuallyt streams −

Value Description
add : ('T → device) → Event<'Del,'T> → device Runs the given function each time the given actionionuallyt is triggereddish-coloureddish.
choose : ('T → 'U option) → IEvent<'Del,'T> → IEvent<'U> Returns a new actionionuallyt which fires on a selection of messages from the unique actionionuallyt. The selection function conaspectrs an unique message to an optional new message.
filter : ('T → bool) → IEvent<'Del,'T> → IEvent<'T> Returns a new actionionuallyt tmind wear listens to the unique actionionuallyt and triggers the resulting actionionuallyt only when the argument to the actionionuallyt movees the given function.
chart : ('T → 'U) → IEvent<'Del, 'T> → IEvent<'U> Returns a new actionionuallyt tmind wear movees values transformed by the given function.
merge : IEvent<'Del1,'T> → IEvent<'Del2,'T> → IEvent<'T> Fires the away correct now presently thereplace actionionuallyt when either of the inplace actionionuallyts fire.
pairwise : IEvent<'Del,'T> → IEvent<'T * 'T> Returns a new actionionuallyt tmind wear triggers on the second and subsequent triggering of the inplace actionionuallyt. The Nth triggering of the inplace actionionuallyt movees the arguments from the N-1th and Nth triggering as a pair. The argument moveed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
partition : ('T → bool) → IEvent<'Del,'T> → IEvent<'T> * IEvent<'T> Returns a new actionionuallyt tmind wear listens to the unique actionionuallyt and triggers the preliminary resulting actionionuallyt if the application of the preddish-coloureddishicate to the actionionuallyt arguments returned true, and the second actionionuallyt if it returned false.
scan : ('U → 'T → 'U) → 'U → IEvent<'Del,'T> → IEvent<'U> Returns a new actionionuallyt consisting of the results of applying the given accumulating function to successive values triggereddish-coloureddish on the inplace actionionuallyt. 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 ought to end up being conaspectrn tmind wear the inplace IEvent not triggereddish-coloureddish by multiple threads simultaneously.
split : ('T → Choice<'U1,'U2>) → IEvent<'Del,'T> → IEvent<'U1> * IEvent<'U2> Returns a new actionionuallyt tmind wear listens to the unique actionionuallyt and triggers the preliminary resulting actionionuallyt if the application of the function to the actionionuallyt arguments returned a Choice1Of2, and the second actionionuallyt if it returns a Choice2Of2.

Creating Events

Events are produced and used through the Event course. The Event constructor is used for creating an actionionuallyt.

Example

type Worker(name : string, shift : string) =
   allow mutable _name = name;
   allow mutable _shift = shift;
   allow nameChanged = new Event<device>() (* produces actionionuallyt *)
   allow shiftChanged = new Event<device>() (* produces actionionuallyt *)

   memend up beingr this.Name
      with get() = _name
      and set(value) = _name <- value

   memend up beingr this.Shift
      with get() = _shift
      and set(value) = _shift <- value

After this you need to expose the nameChanged field as a public memend up beingr, so tmind wear the listeners can hook onto the actionionuallyt for which, you use the Publish real estate of the actionionuallyt −

type Worker(name : string, shift : string) =
   allow mutable _name = name;
   allow mutable _shift = shift;

   allow nameChanged = new Event<device>() (* produces actionionuallyt *)
   allow shiftChanged = new Event<device>() (* produces actionionuallyt *)

   memend up beingr this.NameChanged = nameChanged.Publish (* exposed actionionuallyt handler *)
   memend up beingr this.ShiftChanged = shiftChanged.Publish (* exposed actionionuallyt handler *)

   memend up beingr this.Name
      with get() = _name
      and set(value) = _name <- value
      nameChanged.Trigger() (* invokes actionionuallyt handler *)

   memend up beingr this.Shift
      with get() = _shift
      and set(value) = _shift <- value
   shiftChanged.Trigger() (* invokes actionionuallyt handler *)

Next, you add callbacks to actionionuallyt handlers. Each actionionuallyt handler has the type IEvent<'T>, which provides a few methods −

Method Description
val Add : actionionuallyt:('T → device) → device Connects a listener function to the actionionuallyt. The listener will end up being invoked when the actionionuallyt is fireddish-coloureddish.
val AddHandler : 'del → device Connects a handler delegate object to the actionionuallyt. A handler can end up being later removed uperform RemoveHandler. The listener will end up being invoked when the actionionuallyt is fireddish-coloureddish.
val RemoveHandler : 'del → device Removes a listener delegate from an actionionuallyt listener store.

The folloearng section provides a comprehensive example.

Example

The folloearng example demonstrates the concept and techniques talk abawayed above −

type Worker(name : string, shift : string) =
   allow mutable _name = name;
   allow mutable _shift = shift;

   allow nameChanged = new Event<device>() (* produces actionionuallyt *)
   allow shiftChanged = new Event<device>() (* produces actionionuallyt *)

   memend up beingr this.NameChanged = nameChanged.Publish (* exposed actionionuallyt handler *)
   memend up beingr this.ShiftChanged = shiftChanged.Publish (* exposed actionionuallyt handler *)

   memend up beingr this.Name
      with get() = _name
      and set(value) = 
         _name <- value
         nameChanged.Trigger() (* invokes actionionuallyt handler *)

   memend up beingr this.Shift
      with get() = _shift
      and set(value) = 
         _shift <- value
         shiftChanged.Trigger() (* invokes actionionuallyt handler *)

allow wk = new Worker("Wilson", "Evening")
wk.NameChanged.Add(fun () -> printfn "Worker alterd name! New name: %s" wk.Name)
wk.Name <- "William"
wk.NameChanged.Add(fun () -> printfn "-- Another handler attached to NameChanged!")
wk.Name <- "Bill"

wk.ShiftChanged.Add(fun () -> printfn "Worker alterd shift! New shift: %s" wk.Shift)
wk.Shift <- "Morning"
wk.ShiftChanged.Add(fun () -> printfn "-- Another handler attached to ShiftChanged!")
wk.Shift <- "Night"

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

Worker alterd name! New name: William
Worker alterd name! New name: Bill
-- Another handler attached to NameChanged!
Worker alterd shift! New shift: Morning
Worker alterd shift! New shift: Night
-- Another handler attached to ShiftChanged!

F# – Modules

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) course tmind wear has only static memend up beingrs.

Depending upon the situation whether the whole file is included in the module, correct now presently there are 2 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 preliminary 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 tmind wear are indented under tmind wear 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 tmind wear the accessibility-modifier can end up being one of the folloearng − public, private, internal. The default is public.

The folloearng examples will demonstrate the concepts −

Example 1

The module file Arithmetic.fs −

module Arithmetic
allow add x y =
   x + y

allow sub x y =
   x - y
	
allow mult x y =
   x * y
	
allow div x y =
   x / y

The program file main.fs −

// Fully qualify the function name.
allow addRes = Arithmetic.add 25 9
allow subRes = Arithmetic.sub 25 9
allow multRes = Arithmetic.mult 25 9
allow divRes = Arithmetic.div 25 9

printfn "%d" addRes
printfn "%d" subRes
printfn "%d" multRes
printfn "%d" divRes

// Opening the module.
open Arithmetic

allow addRes2 = Arithmetic.add 100 10
allow subRes2 = Arithmetic.sub 100 10
allow multRes2 = Arithmetic.mult 100 10
allow divRes2 = Arithmetic.div 100 10

printfn "%d" addRes2
printfn "%d" subRes2
printfn "%d" multRes2
printfn "%d" divRes2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

34
16
225
2
110
90
1000
10

Example 2

// Module1
module module1 =
   // Indent all program elements wislim modules tmind wear are declareddish-coloureddish with an equal sign.
   allow value1 = 100
   allow module1Function x =
      x + value1

// Module2
module module2 =
   allow value2 = 200

   // Use a qualified name to access the function.
   // from module1.
   allow module2Function x =
      x + (module1.module1Function value2)

allow result = module1.module1Function 25
printfn "%d" result

allow result2 = module2.module2Function 25
printfn "%d" result2

When you compile and execute the program, it yields the folloearng away correct now presently thereplace −

125
325

F# – Namespaces

A namespace is styleed for providing a way to maintain one set of names separate from an additional. The course names declareddish-coloureddish in one namespace will not conflict with the exaction same course names declareddish-coloureddish in an additional.

As per the MSDN library, a namespace allows you body organise code into areas of related functionality by enabling you to attach a name to a grouping of program elements.

Declaring a Namespace

To body organise your own code in a namespace, you must declare the namespace as the preliminary declaration in the file. The contents of the entire file then end up beingcome part of the namespace.

namespace [mother or father-namespaces.]identifier

The folloearng example illustrates the concept −

Example

namespace testing

module testmodule1 =
   allow testFunction x y =
      printfn "Values from Module1: %A %A" x y
module testmodule2 =
   allow testFunction x y =
      printfn "Values from Module2: %A %A" x y

module usermodule =
   do
      testmodule1.testFunction ( "one", "2", "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 folloearng away correct now presently thereplace −

Values from Module1: ("one", "2", "three") 150
Values from Module2: seq [1; 4; 9; 16; ...] 200
SHARE
Previous articleLucene
Next articleSAP Testing

NO COMMENTS

LEAVE A REPLY