Sei sulla pagina 1di 146

F#QUICKGUIDE

http://www.tutorialspoint.com/fsharp/fsharp_quick_guide.htm

Copyrighttutorialspoint.com

F#OVERVIEW
F#isafunctionalprogramminglanguage.TounderstandF#constructs,youneedtoreadacoupleof
linesabouttheprogrammingparadigmnamedFunctionalProgramming.
Functionalprogrammingtreatscomputerprogramsasmathematicalfunctions.Infunctional
programming,thefocuswouldbeonconstantsandfunctions,insteadofvariablesandstates.Because
functionsandconstantsarethingsthatdontchange.
Infunctionalprogramming,youwillwritemodularprograms,i.e.,theprogramswouldconsistof
functionsthatwilltakeotherfunctionsasinput.
Programswritteninfunctionalprogramminglanguagetendtobeconcise.

AboutF#
FollowingarethebasicinformationaboutF#
Itwasdevelopedin2005atMicrosoftResearch.
ItisapartofMicrosoftsfamilyof.Netlanguage.
Itisafunctionalprogramminglanguage.
ItisbasedonthefunctionalprogramminglanguageOCaml.

FeaturesofF#
Itis.NetimplementationofOCaml.
Itcompiles.NetCLICommonLanguageInterfacebytecodeorMSILMicrosoftIntermediateLanguage
thatrunsonCLRCommonLanguageRuntime.
Itprovidestypeinference.
Itprovidesrichpatternmatchingconstructs.
Ithasinteractivescriptinganddebuggingcapabilities.
Itallowswritinghigherorderfunctions.
Itprovideswelldevelopedobjectmodel.

UseofF#
F#isnormallyusedinthefollowingareas
Makingscientificmodel
Mathematicalproblemsolving
Artificialintelligenceresearchwork

Financialmodelling
Graphicdesign
CPUdesign
Compilerprogramming
Telecommunications
ItisalsousedinCRUDapps,webpages,GUIgamesandothergeneralpurposeprograms.

F#ENVIRONMENTSETUP
ThetoolsrequiredforF#programmingarediscussedinthischapter.

IntegratedDevelopmentEnvironmentIDEforF#
MicrosoftprovidesVisualStudio2013forF#programming.
ThefreeVisualStudio2013CommunityEditionisavailablefromMicrosoftsofficialwebsite.Visual
Studio2013CommunityandabovecomeswiththeVisualF#Tools.TheVisualF#Toolsincludethe
commandlinecompilerfsc. exeandF#Interactivefsi. exe.
Usingthesetools,youcanwriteallkindsofF#programsfromsimplecommandlineapplicationsto
morecomplexapplications.YoucanalsowriteF#sourcecodefilesusingabasictexteditor,like
Notepad,andcompilethecodeintoassembliesusingthecommandlinecompiler.
YoucandownloaditfromMicrosoftVisualStudio.Itgetsautomaticallyinstalledinyourmachine.

WritingF#ProgramsOnLinks
PleasevisittheF#officialwebsiteforthelatestinstructionsongettingthetoolsasaDebianpackageor
compilingthemdirectlyfromthesourcehttp://fsharp.org/use/linux/.

TryitOptionOnline
WehavesetuptheF#Programmingenvironmentonline.Youcaneasilycompileand
executealltheavailableexamplesonlinealongwithdoingyourtheorywork.Itgives
youconfidenceinwhatyouarereadingandtochecktheresultwithdifferentoptions.
Feelfreetomodifyanyexampleandexecuteitonline.
TrythefollowingexampleusingtheTryitoptionorusetheurl
http://www.compileonline.com/.
(*Thisisacomment*)
(*SampleHelloWorldprogramusingF#*)
printfn"HelloWorld!"

Formostoftheexamplesgiveninthistutorial,youwillfindaTryitoptioninour
websitecodesectionsatthetoprightcornerthatwilltakeyoutotheonlinecompiler.So
justmakeuseofitandenjoyyourlearning.

F#PROGRAMSTRUCTURE
F#isaFunctionalProgramminglanguage.
InF#,functionsworklikedatatypes.Youcandeclareanduseafunctioninthesamewaylikeanyother
variable.
Ingeneral,anF#applicationdoesnothaveanyspecificentrypoint.Thecompilerexecutesalltoplevel
statementsinthefilefromtoptobottom.
However,tofollowproceduralprogrammingstyle,manyapplicationskeepasingletoplevelstatement
thatcallsthemainloop.
ThefollowingcodeshowsasimpleF#program
openSystem
(*Thisisamultilinecomment*)
//Thisisasinglelinecomment
letsignnum=
ifnum>0then"positive"
elifnum<0then"negative"
else"zero"
letmain()=
Console.WriteLine("sign5:{0}",(sign5))
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
sign5:positive

Pleasenotethat
AnF#codefilemightbeginwithanumberofopenstatementsthatisusedtoimportnamespaces.
Thebodyofthefilesincludesotherfunctionsthatimplementthebusinesslogicoftheapplication.
Themainloopcontainsthetopexecutablestatements.

F#BASICSYNTAX
YouhaveseenthebasicstructureofanF#program,soitwillbeeasytounderstandotherbasicbuilding
blocksoftheF#programminglanguage.

TokensinF#
AnF#programconsistsofvarioustokens.Atokencouldbeakeyword,anidentifier,aconstant,astring
literal,orasymbol.WecancategorizeF#tokensintotwotypes
Keywords
SymbolandOperators

F#Keywords
Thefollowingtableshowsthekeywordsandbriefdescriptionsofthekeywords.Wewilldiscusstheuse
ofthesekeywordsinsubsequentchapters.

Keyword

Description

abstract

Indicatesamethodthateitherhasnoimplementationinthetypeinwhichitis
declaredorthatisvirtualandhasadefaultimplementation.

and

Usedinmutuallyrecursivebindings,inpropertydeclarations,andwithmultiple
constraintsongenericparameters.

as

Usedtogivethecurrentclassobjectanobjectname.Alsousedtogiveanametoa
wholepatternwithinapatternmatch.

assert

Usedtoverifycodeduringdebugging.

base

Usedasthenameofthebaseclassobject.

begin

Inverbosesyntax,indicatesthestartofacodeblock.

class

Inverbosesyntax,indicatesthestartofaclassdefinition.

default

Indicatesanimplementationofanabstractmethodusedtogetherwithanabstract
methoddeclarationtocreateavirtualmethod.

delegate

Usedtodeclareadelegate.

do

Usedinloopingconstructsortoexecuteimperativecode.

done

Inverbosesyntax,indicatestheendofablockofcodeinaloopingexpression.

downcast

Usedtoconverttoatypethatislowerintheinheritancechain.

downto

Inaforexpression,usedwhencountinginreverse.

elif

Usedinconditionalbranching.Ashortformofelseif.

else

Usedinconditionalbranching.

end

Intypedefinitionsandtypeextensions,indicatestheendofasectionofmember
definitions.
Inverbosesyntax,usedtospecifytheendofacodeblockthatstartswiththebegin
keyword.

exception

Usedtodeclareanexceptiontype.

extern

Indicatesthatadeclaredprogramelementisdefinedinanotherbinaryorassembly.

false

UsedasaBooleanliteral.

finally

Usedtogetherwithtrytointroduceablockofcodethatexecutesregardlessof
whetheranexceptionoccurs.

for

Usedinloopingconstructs.

fun

Usedinlambdaexpressions,alsoknownasanonymousfunctions.

function

Usedasashorteralternativetothefunkeywordandamatchexpressioninalambda
expressionthathaspatternmatchingonasingleargument.

global

Usedtoreferencethetoplevel.NETnamespace.

if

Usedinconditionalbranchingconstructs.

in

Usedforsequenceexpressionsand,inverbosesyntax,toseparateexpressionsfrom
bindings.

inherit

Usedtospecifyabaseclassorbaseinterface.

inline

Usedtoindicateafunctionthatshouldbeintegrateddirectlyintothecaller'scode.

interface

Usedtodeclareandimplementinterfaces.

internal

Usedtospecifythatamemberisvisibleinsideanassemblybutnotoutsideit.

lazy

Usedtospecifyacomputationthatistobeperformedonlywhenaresultisneeded.

let

Usedtoassociate,orbind,anametoavalueorfunction.

let!

Usedinasynchronousworkflowstobindanametotheresultofanasynchronous
computation,or,inothercomputationexpressions,usedtobindanametoaresult,
whichisofthecomputationtype.

match

Usedtobranchbycomparingavaluetoapattern.

member

Usedtodeclareapropertyormethodinanobjecttype.

module

Usedtoassociateanamewithagroupofrelatedtypes,values,andfunctions,to
logicallyseparateitfromothercode.

mutable

Usedtodeclareavariable,thatis,avaluethatcanbechanged.

namespace

Usedtoassociateanamewithagroupofrelatedtypesandmodules,tologically

separateitfromothercode.
new

Usedtodeclare,define,orinvokeaconstructorthatcreatesorthatcancreatean
object.
Alsousedingenericparameterconstraintstoindicatethatatypemusthaveacertain
constructor.

not

null

Notactuallyakeyword.However,notstructincombinationisusedasageneric
parameterconstraint.
Indicatestheabsenceofanobject.
Alsousedingenericparameterconstraints.

of

Usedindiscriminatedunionstoindicatethetypeofcategoriesofvalues,andin
delegateandexceptiondeclarations.

open

Usedtomakethecontentsofanamespaceormoduleavailablewithoutqualification.

or

UsedwithBooleanconditionsasaBooleanoroperator.Equivalentto||.
Alsousedinmemberconstraints.

override

Usedtoimplementaversionofanabstractorvirtualmethodthatdiffersfromthe
baseversion.

private

Restrictsaccesstoamembertocodeinthesametypeormodule.

public

Allowsaccesstoamemberfromoutsidethetype.

rec

Usedtoindicatethatafunctionisrecursive.

return

Usedtoindicateavaluetoprovideastheresultofacomputationexpression.

return!

Usedtoindicateacomputationexpressionthat,whenevaluated,providestheresult
ofthecontainingcomputationexpression.

select

Usedinqueryexpressionstospecifywhatfieldsorcolumnstoextract.Notethatthis
isacontextualkeyword,whichmeansthatitisnotactuallyareservedwordanditonly
actslikeakeywordinappropriatecontext.

static

Usedtoindicateamethodorpropertythatcanbecalledwithoutaninstanceofatype,

oravaluememberthatissharedamongallinstancesofatype.
struct

Usedtodeclareastructuretype.
Alsousedingenericparameterconstraints.
UsedforOCamlcompatibilityinmoduledefinitions.

then

Usedinconditionalexpressions.
Alsousedtoperformsideeffectsafterobjectconstruction.

to

Usedinforloopstoindicatearange.

true

UsedasaBooleanliteral.

try

Usedtointroduceablockofcodethatmightgenerateanexception.Usedtogether
withwithorfinally.

type

Usedtodeclareaclass,record,structure,discriminatedunion,enumerationtype,
unitofmeasure,ortypeabbreviation.

upcast

Usedtoconverttoatypethatishigherintheinheritancechain.

use

UsedinsteadofletforvaluesthatrequireDisposetobecalledtofreeresources.

use!

Usedinsteadoflet!inasynchronousworkflowsandothercomputationexpressions
forvaluesthatrequireDisposetobecalledtofreeresources.

val

Usedinasignaturetoindicateavalue,orinatypetodeclareamember,inlimited
situations.

void

Indicatesthe.NETvoidtype.Usedwheninteroperatingwithother.NETlanguages.

when

UsedforBooleanconditionswhenguardsonpatternmatchesandtointroducea
constraintclauseforagenerictypeparameter.

while

Introducesaloopingconstruct.

with

Usedtogetherwiththematchkeywordinpatternmatchingexpressions.Alsousedin
objectexpressions,recordcopyingexpressions,andtypeextensionstointroduce
memberdefinitions,andtointroduceexceptionhandlers.

yield

Usedinasequenceexpressiontoproduceavalueforasequence.

yield!

Usedinacomputationexpressiontoappendtheresultofagivencomputation

expressiontoacollectionofresultsforthecontainingcomputationexpression.

SomereservedkeywordscamefromtheOCamllanguage

asr

land

lor

lsl

lsr

lxor

mod

sig

SomeotherreservedkeywordsarekeptforfutureexpansionofF#.

atomic

break

checked

component

const

constraint

constructor

continue

eager

event

external

fixed

functor

include

method

mixin

object

parallel

process

protected

pure

sealed

tailcall

trait

virtual

volatile

CommentsinF#
F#providestwotypesofcomments
Onelinecommentstartswith//symbol.
Multilinecommentstartswith andendswith .

ABasicProgramandApplicationEntryPointinF#
Generally,youdonthaveanyexplicitentrypointforF#programs.WhenyoucompileanF#application,
thelastfileprovidedtothecompilerbecomestheentrypointandalltoplevelstatementsinthatfileare
executedfromtoptobottom.
Awellwrittenprogramshouldhaveasingletoplevelstatementthatwouldcallthemainloopofthe
program.
AveryminimalisticF#programthatwoulddisplayHelloWorldonthescreen
(*Thisisacomment*)
(*SampleHelloWorldprogramusingF#*)
printfn"HelloWorld!"

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
HelloWorld!

F#DATATYPES
ThedatatypesinF#canbeclassifiedasfollows

Integraltypes
Floatingpointtypes
Texttypes
Othertypes

IntegralDataType
ThefollowingtableprovidestheintegraldatatypesofF#.Thesearebasicallyintegerdatatypes.

F#
Type

Size

Range

sbyte

1byte

128to127

Example

Remarks

42y

8bitsigned
integer

11y
byte

1byte

0to255

42uy
200uy

int16

2bytes

32768to32767

42s

8bit
unsigned
integer

16bitsigned
integer

11s
uint16

2bytes

0to65,535

42us
200us

int/int32

4bytes

2,147,483,648to2,147,483,647

42
11

uint32

4bytes

0to4,294,967,295

42u
200u

int64

8bytes

9,223,372,036,854,775,808to
9,223,372,036,854,775,807

42L

16bit
unsigned
integer

32bit
signed
integer

32bit
unsigned
integer

64bit
signed

uint64

8bytes

0to18,446,744,073,709,551,615

11L

integer

42UL

64bit
unsigned
integer

200UL
bigint

Atleast4bytes

anyinteger

42I
1499999
9999999
9999999
9999999
9999I

Example
(*singlebyteinteger*)
letx=268.97f
lety=312.58f
letz=x+y
printfn"x:%f"x
printfn"y:%f"y
printfn"z:%f"z
(*unsigned8bitnaturalnumber*)
letp=2uy
letq=4uy
letr=p+q
printfn"p:%i"p
printfn"q:%i"q
printfn"r:%i"r
(*signed16bitinteger*)
leta=12s
letb=24s
letc=a+b
printfn"a:%i"a
printfn"b:%i"b
printfn"c:%i"c

arbitrary
precision
integer

(*signed32bitinteger*)
letd=212l
lete=504l
letf=d+e
printfn"d:%i"d
printfn"e:%i"e
printfn"f:%i"f

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
x:1
y:2
z:3
p:2
q:4
r:6
a:12
b:24
c:36
d:212
e:504
f:716

FloatingPointDataTypes
ThefollowingtableprovidesthefloatingpointdatatypesofF#.

F#Type

Size

Range

float32

4bytes

1.5e45to3.4e38

Example

Remarks

42.0F

32bitsignedfloating
pointnumber
7significantdigits

11.0F
float

8bytes

5.0e324to1.7e308

42.0
11.0

decimal

16bytes

1.0e28to7.9e28

42.0M
11.0M

BigRational

Atleast4bytes

Anyrationalnumber.

42N

64bitsignedfloating
pointnumber
15 16significantdigits

128bitsignedfloating
pointnumber
28 29significantdigits

Arbitraryprecision
rationalnumber.Using
thistyperequiresa

11N

referenceto
FSharp.PowerPack.dll.

Example
(*32bitsignedfloatingpointnumber*)
(*7significantdigits*)
letd=212.098f
lete=504.768f
letf=d+e
printfn"d:%f"d
printfn"e:%f"e
printfn"f:%f"f
(*64bitsignedfloatingpointnumber*)
(*1516significantdigits*)
letx=21290.098
lety=50446.768
letz=x+y
printfn"x:%g"x
printfn"y:%g"y
printfn"z:%g"z

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

TextDataTypes
ThefollowingtableprovidesthetextdatatypesofF#.

F#Type

Size

Range

char

2bytes

U+0000toU+ffff

Example

Remarks

'x'

Singleunicode
characters

'\t'
string

20+2 string slength


bytes

0toabout2billion
characters

"Hello"

Unicodetext

"World"

Example
letchoice='y'
letname="ZaraAli"
letorg="TutorialsPoint"
printfn"Choice:%c"choice
printfn"Name:%s"name
printfn"Organisation:%s"org

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Choice:y
Name:ZaraAli
Organisation:TutorialsPoint

OtherDataTypes
ThefollowingtableprovidessomeotherdatatypesofF#.

F#Type

Size

Range

Example

Remarks

bool

1byte

Onlytwopossiblevalues,trueor
false

true

Storesboolean
values

false

Example
lettrueVal=true
letfalseVal=false
printfn"TrueValue:%b"(trueVal)
printfn"FalseValue:%b"(falseVal)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
TrueValue:true
FalseValue:false

F#VARIABLES
Avariableisanamegiventoastorageareathatourprogramscanmanipulate.Eachvariablehasa
specifictype,whichdeterminesthesizeandlayoutofthevariable'smemorytherangeofvaluesthatcan
bestoredwithinthatmemoryandthesetofoperationsthatcanbeappliedtothevariable.

VariableDeclarationinF#
Theletkeywordisusedforvariabledeclaration
Forexample,
letx=10

Itdeclaresavariablexandassignsthevalue10toit.
Youcanalsoassignanexpressiontoavariable
letx=10
lety=20
letz=x+y

Thefollowingexampleillustratestheconcept

Example
letx=10
lety=20
letz=x+y
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
x:10
y:20
z:30

VariablesinF#areimmutable,whichmeansonceavariableisboundtoavalue,itcantbechanged.
Theyareactuallycompiledasstaticreadonlyproperties.
Thefollowingexampledemonstratesthis.

Example
letx=10
lety=20
letz=x+y
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z
letx=15
lety=20
letz=x+y

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

Whenyoucompileandexecutetheprogram,itshowsthefollowingerrormessage
Duplicatedefinitionofvalue'x'
Duplicatedefinitionofvalue'Y'
Duplicatedefinitionofvalue'Z'

VariableDefinitionWithTypeDeclaration
Avariabledefinitiontellsthecompilerwhereandhowmuchstorageforthevariableshouldbecreated.A
variabledefinitionmayspecifyadatatypeandcontainsalistofoneormorevariablesofthattypeas
showninthefollowingexample.

Example
letx:int32=10
lety:int32=20
letz:int32=x+y
printfn"x:%d"x
printfn"y:%d"y
printfn"z:%d"z
letp:float=15.99
letq:float=20.78
letr:float=p+q
printfn"p:%g"p
printfn"q:%g"q
printfn"r:%g"r

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

MutableVariables
Attimesyouneedtochangethevaluesstoredinavariable.Tospecifythattherecouldbeachangeinthe
valueofadeclaredandassignedvariable,inlaterpartofaprogram,F#providesthemutablekeyword.
Youcandeclareandassignmutablevariablesusingthiskeyword,whosevaluesyouwillchange.
Themutablekeywordallowsyoutodeclareandassignvaluesinamutablevariable.
Youcanassignsomeinitialvaluetoamutablevariableusingtheletkeyword.However,toassignnew
subsequentvaluetoit,youneedtousetheoperator.

Forexample,
letmutablex=10
x15

Thefollowingexamplewillcleartheconcept

Example
letmutablex=10
lety=20
letmutablez=x+y
printfn"OriginalValues:"
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z
printfn"Letuschangethevalueofx"
printfn"Valueofzwillchangetoo."
x<15
z<x+y
printfn"NewValues:"
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
OriginalValues:
x:10
y:20
z:30
Letuschangethevalueofx
Valueofzwillchangetoo.
NewValues:
x:15
y:20
z:35

F#OPERATORS
Anoperatorisasymbolthattellsthecompilertoperformspecificmathematicalorlogical
manipulations.F#isrichinbuiltinoperatorsandprovidesthefollowingtypesofoperators
ArithmeticOperators
ComparisonOperators
BooleanOperators
BitwiseOperators

ArithmeticOperators

ThefollowingtableshowsallthearithmeticoperatorssupportedbyF#language.AssumevariableA
holds10andvariableBholds20then

Operator

Description

Example

Addstwooperands

A+Bwillgive30

Subtractssecondoperandfromthefirst

ABwillgive10

Multipliesbothoperands

A*Bwillgive200

Dividesnumeratorbydenumerator

B/Awillgive2

ModulusOperatorandremainderofafteranintegerdivision

B%Awillgive0

**

ExponentiationOperator,raisesanoperandtothepowerof
another

B**Awillgive2010

Example
leta:int32=21
letb:int32=10
letmutablec=a+b
printfn"Line1Valueofcis%d"c
c<ab;
printfn"Line2Valueofcis%d"c
c<a*b;
printfn"Line3Valueofcis%d"c
c<a/b;
printfn"Line4Valueofcis%d"c
c<a%b;
printfn"Line5Valueofcis%d"c

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Line1Valueofcis31
Line2Valueofcis11
Line3Valueofcis210
Line4Valueofcis2
Line5Valueofcis1

ComparisonOperators
ThefollowingtableshowsallthecomparisonoperatorssupportedbyF#language.Thesebinary
comparisonoperatorsareavailableforintegralandfloatingpointtypes.Theseoperatorsreturnvalues

oftypebool.
AssumevariableAholds10andvariableBholds20,then

Operator

Description

Example

Checksifthevaluesoftwooperandsareequalornot,ifyes
thenconditionbecomestrue.

A == Bisnottrue.

<>

Checksifthevaluesoftwooperandsareequalornot,ifvalues
arenotequalthenconditionbecomestrue.

A <> Bistrue.

>

Checksifthevalueofleftoperandisgreaterthanthevalueof
rightoperand,ifyesthenconditionbecomestrue.

A > Bisnottrue.

<

Checksifthevalueofleftoperandislessthanthevalueofright
operand,ifyesthenconditionbecomestrue.

A < Bistrue.

>=

Checksifthevalueofleftoperandisgreaterthanorequalto
thevalueofrightoperand,ifyesthenconditionbecomestrue.

A >= Bisnottrue.

<=

Checksifthevalueofleftoperandislessthanorequaltothe
valueofrightoperand,ifyesthenconditionbecomestrue.

A <= Bistrue.

Example
letmutablea:int32=21
letmutableb:int32=10
if(a=b)then
printfn"Line1aisequaltob"
else
printfn"Line1aisnotequaltob"
if(a<b)then
printfn"Line2aislessthanb"
else
printfn"Line2aisnotlessthanb"
if(a>b)then
printfn"Line3aisgreaterthanb"
else
printfn"Line3aisnotgreaterthanb"
(*Letschangevalueofaandb*)
a<5
b<20
if(a<=b)then
printfn"Line4aiseitherlessthanorequaltob"

else
printfn"Line4aisaisgreaterthanb"

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Line1aisnotequaltob
Line2aisnotlessthanb
Line3aisgreaterthanb
Line4aiseitherlessthanorequaltob

BooleanOperators
ThefollowingtableshowsalltheBooleanoperatorssupportedbyF#language.AssumevariableAholds
trueandvariableBholdsfalse,then

Operator

Description

&&

CalledBooleanANDoperator.Ifboththeoperandsarenon
zero,thenconditionbecomestrue.

||

CalledBooleanOROperator.Ifanyofthetwooperandsis
nonzero,thenconditionbecomestrue.

A | | Bistrue.

not

CalledBooleanNOTOperator.Usetoreversesthelogical
stateofitsoperand.IfaconditionistruethenLogicalNOT
operatorwillmakefalse.

not A&&B istrue.

Example
letmutablea:bool=true;
letmutableb:bool=true;
if(a&&b)then
printfn"Line1Conditionistrue"
else
printfn"Line1Conditionisnottrue"
if(a||b)then
printfn"Line2Conditionistrue"
else
printfn"Line2Conditionisnottrue"
(*letschangethevalueofa*)
a<false
if(a&&b)then
printfn"Line3Conditionistrue"
else
printfn"Line3Conditionisnottrue"

Example
A&&B isfalse.

if(a||b)then
printfn"Line4Conditionistrue"
else
printfn"Line4Conditionisnottrue"

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Line1Conditionistrue
Line2Conditionistrue
Line3Conditionisnottrue
Line4Conditionistrue

BitwiseOperators
Bitwiseoperatorsworkonbitsandperformbitbybitoperation.Thetruthtablesfor&&&bitwiseAND,
|||bitwiseOR,and^^^bitwiseexclusiveORareasfollows

p&&&q

p|||q

p^^^q

AssumeifA=60andB=13nowinbinaryformattheywillbeasfollows
A=00111100
B=00001101

A&&&B=00001100
A|||B=00111101
A^^^B=00110001
~~~A=11000011
TheBitwiseoperatorssupportedbyF#languagearelistedinthefollowingtable.AssumevariableA
holds60andvariableBholds13,then

Operator

Description

&&&

BinaryANDOperatorcopiesabittotheresultifitexists
inbothoperands.

Example
A&&&B willgive12,

whichis00001100

|||

BinaryOROperatorcopiesabitifitexistsineither
operand.

A | | | Bwillgive61,whichis
00111101

^^^

BinaryXOROperatorcopiesthebitifitissetinone
operandbutnotboth.

A^^^B willgive49,which

is00110001

~~~

BinaryOnesComplementOperatorisunaryandhasthe
effectof'flipping'bits.

Awillgive61,whichis
11000011in2's
complementform.

<<<

BinaryLeftShiftOperator.Theleftoperandsvalueis
movedleftbythenumberofbitsspecifiedbytheright
operand.

A<<<2willgive240which
is11110000

>>>

BinaryRightShiftOperator.Theleftoperandsvalueis
movedrightbythenumberofbitsspecifiedbytheright
operand.

A>>>2willgive15whichis
00001111

Example
leta:int32=60//60=00111100
letb:int32=13//13=00001101
letmutablec:int32=0
c<a&&&b//12=00001100
printfn"Line1Valueofcis%d"c
c<a|||b//61=00111101
printfn"Line2Valueofcis%d"c
c<a^^^b//49=00110001
printfn"Line3Valueofcis%d"c
c=~~~a//61=11000011
printfn"Line4Valueofcis%d"c
c<a<<<2//240=11110000
printfn"Line5Valueofcis%d"c
c<a>>>2//15=00001111
printfn"Line6Valueofcis%d"c

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Line1Valueofcis12
Line2Valueofcis61
Line3Valueofcis49
Line4Valueofcis49
Line5Valueofcis240
Line6Valueofcis15

OperatorsPrecedence
ThefollowingtableshowstheorderofprecedenceofoperatorsandotherexpressionkeywordsintheF#
language,fromlowestprecedencetothehighestprecedence.

Operator

Associativity

as

Right

when

Right

|pipe

Left

Right

let

Nonassociative

function,fun,match,try

Nonassociative

if

Nonassociative

Right

:=

Right

Nonassociative

or,||

Left

&,&&

Left

<op,>op,=,|op,&op

Left

&&&,|||,^^^,~~~,<<<,>>>

Left

^op

Right

::

Right

:?>,:?

Nonassociative

op,+op,binary

Left

*op,/op,%op

Left

**op

Right

fxfunctionapplication

Left

|patternmatch

Right

prefixoperators+ op, op,

Left

Left

fx

Left

f<types>

Left

Example
leta:int32=20
letb:int32=10
letc:int32=15
letd:int32=5
letmutablee:int32=0
e<(a+b)*c/d//(30*15)/5
printfn"Valueof(a+b)*c/dis:%d"e
e<((a+b)*c)/d//(30*15)/5
printfn"Valueof((a+b)*c)/dis:%d"e
e<(a+b)*(c/d)//(30)*(15/5)
printfn"Valueof(a+b)*(c/d)is:%d"e
e<a+(b*c)/d//20+(150/5)
printfn"Valueofa+(b*c)/dis:%d"e

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Valueof(a+b)*c/dis:90
Valueof((a+b)*c)/dis:90
Valueof(a+b)*(c/d)is:90
Valueofa+(b*c)/dis:50

F#DECISIONMAKING
Decisionmakingstructuresrequirethattheprogrammerspecifyoneormoreconditionstobeevaluated
ortestedbytheprogram.Itshouldbealongwithastatementorstatementstobeexecutedifthe
conditionisdeterminedtobetrue,andoptionally,otherstatementstobeexecutediftheconditionis
determinedtobefalse.
Followingisthegeneralformofatypicaldecisionmakingstructurefoundinmostoftheprogramming
languages

F#programminglanguageprovidesthefollowingtypesofdecisionmakingstatements.

Statement

Description

if/thenstatement

Anif/thenstatementconsistsofaBooleanexpressionfollowed
byoneormorestatements.

if/then/elsestatement

Anif/thenstatementcanbefollowedbyanoptionalelse
statement,whichexecuteswhentheBooleanexpressionisfalse.

if/then/elif/elsestatement

Anif/then/elif/elsestatementallowsyoutohavemultipleelse
branches.

nestedifstatements

Youcanuseoneiforelseifstatementinsideanotheriforelseif
statements.

F#if/thenStatement
Anif/thenstatementconsistsofaBooleanexpressionfollowedbyoneormorestatements.

Syntax
Theif/thenconstructinF#hasthefollowingsyntax

(*simpleif*)
ifexprthen
expr

Flowdiagram

Example
leta:int32=10
(*checkthebooleanconditionusingifstatement*)
if(a<20)then
printfn"aislessthan20\n"
printfn"Valueofais:%d"a

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
aislessthan20
Valueofais:10

F#if/then/elseStatement
Anif/thenstatementcanbefollowedbyanoptionalelsestatement,whichexecuteswhentheBoolean
expressionisfalse.

Syntax

Thesyntaxofanif/then/elsestatementinF#programminglanguageis
ifexprthen
expr
else
expr

FlowDiagram

Example
leta:int32=100
(*checkthebooleanconditionusingifstatement*)
if(a<20)then
printfn"aislessthan20\n"
else
printfn"aisnotlessthan20\n"
printfn"Valueofais:%d"a

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
aisnotlessthan20
Valueofais:100

F#if/then/elif/elseStatement

Anif/then/elif/elseconstructhasmultipleelsebranches.

Syntax
Thesyntaxofanif/then/elif/elsestatementinF#programminglanguageis
ifexprthen
expr
elifexprthen
expr
elifexprthen
expr
...
else
expr

Example
leta:int32=100
(*checkthebooleanconditionusingifstatement*)
if(a=10)then
printfn"Valueofais10\n"
elif(a=20)then
printfn"Valueofais20\n"
elif(a=30)then
printfn"Valueofais30\n"
else
printfn"Noneofthevaluesarematching\n"
printfn"Valueofais:%d"a

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Noneofthevaluesarematching
Valueofais:100

F#NestedifStatements
ItisalwayslegalinF#programmingtonestif/thenorif/then/elsestatements,whichmeansyoucanuse
oneiforelseifstatementinsideanotheriforelseifstatements.

Syntax
ifexprthen
expr
ifexprthen
expr
else
expr
else
expr

Example
leta:int32=100
letb:int32=200
(*checkthebooleanconditionusingifstatement*)
if(a=100)then
(*ifconditionistruethencheckthefollowing*)
if(b=200)then
printfn"Valueofais100andbis200\n"
printfn"Exactvalueofais:%d"a
printfn"Exactvalueofbis:%d"b

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Valueofais100andbis200
Exactvalueofais:100
Exactvalueofbis:200

F#LOOPS
Programminglanguagesprovidevariouscontrolstructuresthatallowformorecomplicatedexecution
paths.
Aloopstatementallowsustoexecuteastatementorgroupofstatementsmultipletimesandfollowingis
thegeneralformofaloopstatementinmostoftheprogramminglanguages

F#providesthefollowingtypesofloopstohandletheloopingrequirements.

LoopType

Description

fortoandfordowntoexpressions

Thefor...toexpressionisusedtoiterateinaloopover
arangeofvaluesofaloopvariable.Thefordownto
expressionreducesthevalueofloopvariable.

forinexpression

Thisformofforloopisusedtoiterateovercollections
ofitemsi.e.,loopsovercollectionsandsequences

Whiledoloop

Repeatsastatementorgroupofstatementswhilea
givenconditionistrue.Itteststheconditionbefore
executingtheloopbody.

nestedloops

Youcanuseoneormoreloopinsideanyotherforor
whileloop.

F#for...toandfor...downtoExpressions
Aforloopisarepetitioncontrolstructurethatallowsyoutoefficientlywritealoopthatneedsto
executeaspecificnumberoftimes.

Syntax
ThesyntaxofafortoloopinF#programminglanguageis
forvar=startexprtoendexprdo
...//loopbody

ThesyntaxofafordowntoloopinF#programminglanguageis
forvar=startexprdowntoendexprdo
...//loopbody

Example1
Thefollowingprogramprintsoutthenumbers120
letmain()=
fori=1to20do
printfn"i:%i"i
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
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

Example2
Thefollowingprogramcountsinreverseandprintsoutthenumbers201
letmain()=
fori=20downto1do
printfn"i:%i"i
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
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...inExpressions
Thisloopingconstructisusedtoiterateoverthematchesofapatterninanenumerablecollectionsuch
asarangeexpression,sequence,list,array,orotherconstructthatsupportsenumeration.

Syntax
forpatterninenumerableexpressiondo
bodyexpression

Example
Thefollowingprogramillustratestheconcept
//Loopingoveralist.
letlist1=[10;25;34;45;78]
foriinlist1do
printfn"%d"i
//Loopingoverasequence.
letseq1=seq{foriin1..10>(i,i*i)}
for(a,asqr)inseq1do
printfn"%dsquaredis%d"aasqr

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
10
25
34
45
78

1squaredis1
2squaredis4
3squaredis9
4squaredis16
5squaredis25
6squaredis36
7squaredis49
8squaredis64
9squaredis81
10squaredis100

F#WhiledoExpressions
Thewhile...doexpressionisusedtoperformiterativeexecutionwhileaspecifiedtestconditionistrue.

Syntax
whiletestexpressiondo
bodyexpression

Thetestexpressionisevaluatedfirstifitistrue,thebodyexpressionisexecutedandthetest
expressionisevaluatedagain.Thebodyexpressionmusthavetypeunit,i.e.,itshouldnotreturnany
value.Ifthetestexpressionisfalse,theiterationends.

Example
letmutablea=10
while(a<20)do
printfn"valueofa:%d"a
a<a+1

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
valueofa:19

F#NestedLoops
F#programminglanguageallowstouseoneloopinsideanotherloop.

Syntax
Thesyntaxforanestedforloopstatementcouldbeasfollows
forvar1=startexpr1toendexpr1do

forvar2=startexpr2toendexpr2do
...//loopbody

Thesyntaxforanestedwhileloopstatementcouldbeasfollows
whiletestexpression1do
whiletestexpression2do
bodyexpression

Example
letmain()=
fori=1to5do
printf"\n"
forj=1to3do
printf"*"
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
***
***
***
***
***

F#FUNCTIONS
InF#,functionsworklikedatatypes.Youcandeclareanduseafunctioninthesamewaylikeanyother
variable.
Sincefunctionscanbeusedlikeanyothervariables,youcan
Createafunction,withanameandassociatethatnamewithatype.
Assignitavalue.
Performsomecalculationonthatvalue.
Passitasaparametertoanotherfunctionorsubroutine.
Returnafunctionastheresultofanotherfunction.

DefiningaFunction
Functionsaredefinedbyusingtheletkeyword.Afunctiondefinitionhasthefollowingsyntax
let[inline]functionnameparameterlist[:returntype]
=functionbody

Where,
functionnameisanidentifierthatrepresentsthefunction.
parameterlistgivesthelistofparametersseparatedbyspaces.Youcanalsospecifyanexplicit

typeforeachparameterandifnotspecifiedcompilertendstodeduceitfromthefunctionbody
likevariables.
functionbodyconsistsofanexpression,oracompoundexpressionconsistingofanumberof
expressions.Thefinalexpressioninthefunctionbodyisthereturnvalue.
returntypeisacolonfollowedbyatypeandisoptional.Ifthereturntypeisnotspecified,then
thecompilerdeterminesitfromthefinalexpressioninthefunctionbody.

ParametersofaFunction
Youlistthenamesofparametersrightafterthefunctionname.Youcanspecifythetypeofaparameter.
Thetypeoftheparametershouldfollowthenameoftheparameterseparatedbyacolon.
Ifnoparametertypeisspecified,itisinferredbythecompiler.
Forexample
letdoubleIt(x:int)=2*x

CallingaFunction
Afunctioniscalledbyspecifyingthefunctionnamefollowedbyaspaceandthenanyarguments
separatedbyspaces.
Forexample
letvol=cylinderVolume3.05.0

Thefollowingprogramsillustratetheconcepts.

Example1
Thefollowingprogramcalculatesthevolumeofacylinderwhentheradiusandlengtharegivenas
parameters.
//thefunctioncalculatesthevolumeof
//acylinderwithradiusandlengthasparameters
letcylinderVolumeradiuslength:float=
//functionbody
letpi=3.14159
length*pi*radius*radius
letvol=cylinderVolume3.05.0
printfn"Volume:%g"vol

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Volume:141.372

Example2

Thefollowingprogramreturnsthelargervalueoftwogivenparameters
//thefunctionreturnsthelargervaluebetweentwo
//arguments
letmaxnum1num2:int32=
//functionbody
if(num1>num2)then
num1
else
num2
letres=max3952
printfn"MaxValue:%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
MaxValue:52

Example3
letdoubleIt(x:int)=2*x
printfn"Double19:%d"(doubleIt(19))

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Double19:38

RecursiveFunctions
Recursivefunctionsarefunctionsthatcallthemselves.
Youdefinearecursiveusingtheletreckeywordcombination.
Syntaxfordefiningarecursivefunctionis
//Recursivefunctiondefinition
letrecfunctionnameparameterlist=recursivefunctionbody

Forexample
letrecfibn=ifn<2then1elsefib(n1)+fib(n2)

Example1
ThefollowingprogramreturnsFibonacci1to10
letrecfibn=ifn<2then1elsefib(n1)+fib(n2)
fori=1to10do
printfn"Fibonacci%d:%d"i(fibi)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput

Fibonacci1:1
Fibonacci2:2
Fibonacci3:3
Fibonacci4:5
Fibonacci5:8
Fibonacci6:13
Fibonacci7:21
Fibonacci8:34
Fibonacci9:55
Fibonacci10:89

Example2
Thefollowingprogramreturnsfactorial8
openSystem
letrecfactx=
ifx<1then1
elsex*fact(x1)
Console.WriteLine(fact8)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
40320

ArrowNotationsinF#
F#reportsaboutdatatypeinfunctionsandvalues,usingachainedarrownotation.Letustakean
exampleofafunctionthattakesoneintinput,andreturnsastring.Inarrownotation,itiswrittenas
int>string

Datatypesarereadfromlefttoright.
Letustakeanotherhypotheticalfunctionthattakestwointdatainputsandreturnsastring.
letmydivfunctionxy=(x/y).ToString();;

F#reportsthedatatypeusingchainedarrownotationas
valmydivfunction:x:int>y:int>string

Thereturntypeisrepresentedbytherightmostdatatypeinchainedarrownotation.
Somemoreexamples

Notation

Meaning

floatfloatfloat

Thefunctiontakestwofloatinputs,returnsanotherfloat.

intstringfloat

Thefunctiontakesanintandastringinput,returnsafloat.

LambdaExpressions
Alambdaexpressionisanunnamedfunction.
Letustakeanexampleoftwofunctions
letapplyFunction(f:int>int>int)xy=fxy
letmulxy=x*y
letres=applyFunctionmul57
printfn"%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
35

Nowintheaboveexample,ifinsteadofdefiningthefunctionmul,wecouldhaveusedlambda
expressionsas
letapplyFunction(f:int>int>int)xy=fxy
letres=applyFunction(funxy>x*y)57
printfn"%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
35

FunctionCompositionandPipelining
InF#,onefunctioncanbecomposedfromotherfunctions.
Thefollowingexampleshowsthecompositionofafunctionnamedf,fromtwofunctionsfunction1and
function2
letfunction1x=x+1
letfunction2x=x*5
letf=function1>>function2
letres=f10
printfn"%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
55

F#alsoprovidesafeaturecalledpipeliningoffunctions.Pipeliningallowsfunctioncallstobe
chainedtogetherassuccessiveoperations.
Thefollowingexampleshowsthat

letfunction1x=x+1
letfunction2x=x*5
letres=10|>function1|>function2
printfn"%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
55

F#STRINGS
InF#,thestringtyperepresentsimmutabletextasasequenceofUnicodecharacters.

StringLiterals
Stringliteralsaredelimitedbythequotationmark " character.
Somespecialcharactersarethereforspecialuseslikenewline,tab,etc.Theyareencodedusing
backslash(\)character.Thebackslashcharacterandtherelatedcharactermaketheescapesequence.
ThefollowingtableshowstheescapesequencesupportedbyF#.

Character

Escapesequence

Backspace

\b

Newline

\n

Carriagereturn

\r

Tab

\t

Backslash

\\

Quotationmark

\"

Apostrophe

\'

Unicodecharacter

\uXXXXor\UXXXXXXXXwhereXindicatesahexadecimaldigit

WaysoflgnoringtheEscapeSequence
Thefollowingtwowaysmakesthecompilerignoretheescapesequence
Usingthe@symbol.
Enclosingthestringintriplequotes.
Whenastringliteralisprecededbythe@symbol,itiscalledaverbatimstring.Inthatway,allescape
sequencesinthestringareignored,exceptthattwoquotationmarkcharactersareinterpretedasone

quotationmarkcharacter.
Whenastringisenclosedbytriplequotes,thenalsoallescapesequencesareignored,includingdouble
quotationmarkcharacters.

Example
ThefollowingexampledemonstratesthistechniqueshowinghowtoworkwithXMLorotherstructures
thatincludeembeddedquotationmarks
//Usingaverbatimstring
letxmldata=@"<bookauthor=""Lewis,C.S""title=""Narnia"">"
printfn"%s"xmldata

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
<bookauthor="Lewis,C.S"title="Narnia">

BasicOperatorsonStrings
Thefollowingtableshowsthebasicoperationsonstrings

Value

Description

collect:char stringstringstring

Createsanewstringwhosecharactersarethe
resultsofapplyingaspecifiedfunctiontoeachof
thecharactersoftheinputstringand
concatenatingtheresultingstrings.

concat:stringseq<string>string

Returnsanewstringmadebyconcatenatingthe
givenstringswithaseparator.

exists:char boolstringbool

Testsifanycharacterofthestringsatisfiesthe
givenpredicate.

forall:char boolstringbool

Testsifallcharactersinthestringsatisfythegiven
predicate.

init:intint stringstring

Createsanewstringwhosecharactersarethe
resultsofapplyingaspecifiedfunctiontoeach
indexandconcatenatingtheresultingstrings.

iter:char unitstringunit

Appliesaspecifiedfunctiontoeachcharacterin
thestring.

iteri:int char unitstringunit

Appliesaspecifiedfunctiontotheindexofeach
characterinthestringandthecharacteritself.

length:stringint

Returnsthelengthofthestring.

map:char charstringstring

Createsanewstringwhosecharactersarethe
resultsofapplyingaspecifiedfunctiontoeachof
thecharactersoftheinputstring.

mapi:int char charstringstring

Createsanewstringwhosecharactersarethe
resultsofapplyingaspecifiedfunctiontoeach
characterandindexoftheinputstring.

replicate:intstringstring

Returnsastringbyconcatenatingaspecified
numberofinstancesofastring.

Thefollowingexamplesdemonstratetheusesofsomeoftheabovefunctionalities

Example1
TheString.collectfunctionbuildsanewstringwhosecharactersaretheresultsofapplyingaspecified
functiontoeachofthecharactersoftheinputstringandconcatenatingtheresultingstrings.
letcollectTestinginputS=
String.collect(func>sprintf"%c"c)inputS
printfn"%s"(collectTesting"HappyNewYear!")

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
HappyNewYear!

Example2
TheString.concatfunctionconcatenatesagivensequenceofstringswithaseparatorandreturnsanew
string.
letstrings=["TutorialsPoint";"CodingGround";"AbsoluteClasses"]
letourProducts=String.concat"\n"strings
printfn"%s"ourProducts

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
TutorialsPoint
CodingGround
AbsoluteClasses

Example3
TheString.replicatemethodreturnsastringbyconcatenatingaspecifiednumberofinstancesofastring.
printfn"%s"<|String.replicate10"*!"

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
*!*!*!*!*!*!*!*!*!*!

F#OPTIONS
TheoptiontypeinF#isusedincalculationswhentheremayormaynotexistavalueforavariableor
function.Optiontypesareusedforrepresentingoptionalvaluesincalculations.Theycanhavetwo
possiblevaluesSomexorNone.
Forexample,afunctionperformingadivisionwillreturnavalueinnormalsituation,butwillthrow
exceptionsincaseofazerodenominator.Usingoptionsherewillhelptoindicatewhetherthefunction
hassucceededorfailed.
Anoptionhasanunderlyingtypeandcanholdavalueofthattype,oritmightnothaveavalue.

UsingOptions
Letustaketheexampleofdivisionfunction.Thefollowingprogramexplainsthis
Letuswriteafunctiondiv,andsendtwoargumentstoit20and5
letdivxy=x/y
letres=div205
printfn"Result:%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Result:4

Ifthesecondargumentiszero,thentheprogramthrowsanexception
letdivxy=x/y
letres=div200
printfn"Result:%d"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
UnhandledException:
System.DivideByZeroException:Divisionbyzero

Insuchcases,wecanuseoptiontypestoreturnSomevaluewhentheoperationissuccessfulorNoneif
theoperationfails.
Thefollowingexampledemonstratestheuseofoptions

Example
letdivxy=
matchywith
|0>None
|_>Some(x/y)

letres:intoption=div204
printfn"Result:%A"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Result:Some5

OptionPropertiesandMethods
Theoptiontypesupportsthefollowingpropertiesandmethods

Propertyormethod

Type

Description

None

'Toption

Astaticpropertythatenablesyoutocreateanoption
valuethathastheNonevalue.

IsNone

bool

ReturnstrueiftheoptionhastheNonevalue.

IsSome

bool

Returnstrueiftheoptionhasavaluethatisnot
None.

Some

'Toption

Astaticmemberthatcreatesanoptionthathasavalue
thatisnotNone.

Value

'T

Returnstheunderlyingvalue,orthrowsa
NullReferenceExceptionifthevalueisNone.

Example1
letcheckPositive(a:int)=
ifa>0then
Some(a)
else
None
letres:intoption=checkPositive(31)
printfn"Result:%A"res

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Result:<null>

Example2
letdivxy=
matchywith
|0>None
|_>Some(x/y)

letres:intoption=div204
printfn"Result:%A"res
printfn"Result:%A"res.Value

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Result:Some5
Result:5

Example3
letisHundred=function
|Some(100)>true
|Some(_)|None>false
printfn"%A"(isHundred(Some(45)))
printfn"%A"(isHundred(Some(100)))
printfn"%A"(isHundredNone)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
false
true
false

F#TUPLES
Atupleisacommaseparatedcollectionofvalues.Theseareusedforcreatingadhocdatastructures,
whichgrouptogetherrelatedvalues.
Forexample,ZaraAli, Hyderabad, 10isa3tuplewithtwostringvaluesandanintvalue,ithasthetype
string string int.
Tuplescouldbepairs,triples,andsoon,ofthesameordifferenttypes.
Someexamplesareprovidedhere
//Tupleoftwointegers.
(4,5)
//Tripleofstrings.
("one","two","three")
//Tupleofunknowntypes.
(a,b)
//Tuplethathasmixedtypes.
("AbsoluteClasses",1,2.0)
//Tupleofintegerexpressions.
(a*4,b+7)

Example

Thisprogramhasafunctionthattakesatupleoffourfloatvaluesandreturnstheaverage
letaverageFour(a,b,c,d)=
letsum=a+b+c+d
sum/4.0
letavg:float=averageFour(4.0,5.1,8.0,12.0)
printfn"Avgoffournumbers:%f"avg

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Avgoffournumbers:7.275000

AccessingIndividualTupleMembers
Theindividualmembersofatuplecouldbeassessedandprintedusingpatternmatching.
Thefollowingexampleillustratestheconcept

Example
letdisplaytuple1=
matchtuple1with
|(a,b,c)>printfn"DetailInfo:%A%A%A"abc
display("ZaraAli","Hyderabad",10)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
DetailInfo:"ZaraAli""Hyderabad"10

F#hastwobuiltinfunctions,fstandsnd,whichreturnthefirstandseconditemsina2tuple.
Thefollowingexampleillustratestheconcept

Example
printfn"Firstmember:%A"(fst(23,30))
printfn"Secondmember:%A"(snd(23,30))
printfn"Firstmember:%A"(fst("Hello","World!"))
printfn"Secondmember:%A"(snd("Hello","World!"))
letnameTuple=("Zara","Ali")
printfn"FirstName:%A"(fstnameTuple)
printfn"SecondName:%A"(sndnameTuple)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Firstmember:23
Secondmember:30
Firstmember:"Hello"

Secondmember:"World!"
FirstName:"Zara"
SecondName:"Ali"

F#RECORDS
Arecordissimilartoatuple,howeveritcontainsnamedfields.Forexample,
typewebsite=
{title:string;
url:string}

DefiningRecord
Arecordisdefinedasatypeusingthetypekeyword,andthefieldsoftherecordaredefinedasa
semicolonseparatedlist.
Syntaxfordefiningarecordis
typerecordName=
{[fieldName:dataType]+}

CreatingaRecord
Youcancreatearecordbyspecifyingtherecord'sfields.Forexample,letuscreateawebsiterecord
namedhomepage
lethomepage={Title="TutorialsPoint";Url="www.tutorialspoint.com"}

Thefollowingexampleswillexplaintheconcepts

Example1
Thisprogramdefinesarecordtypenamedwebsite.Thenitcreatessomerecordsoftypewebsiteand
printstherecords.
(*definingarecordtypenamedwebsite*)
typewebsite=
{Title:string;
Url:string}
(*creatingsomerecords*)
lethomepage={Title="TutorialsPoint";Url="www.tutorialspoint.com"}
letcpage={Title="LearnC";Url="www.tutorialspoint.com/cprogramming/index.htm"}
letfsharppage={Title="LearnF#";Url="www.tutorialspoint.com/fsharp/index.htm"}
letcsharppage={Title="LearnC#";Url="www.tutorialspoint.com/csharp/index.htm"}
(*printingrecords*)
(printfn"HomePage:Title:%A\n\tURL:%A")homepage.Titlehomepage.Url
(printfn"CPage:Title:%A\n\tURL:%A")cpage.Titlecpage.Url
(printfn"F#Page:Title:%A\n\tURL:%A")fsharppage.Titlefsharppage.Url
(printfn"C#Page:Title:%A\n\tURL:%A")csharppage.Titlecsharppage.Url

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput

HomePage:Title:"TutorialsPoint"
URL:"www.tutorialspoint.com"
CPage:Title:"LearnC"
URL:"www.tutorialspoint.com/cprogramming/index.htm"
F#Page:Title:"LearnF#"
URL:"www.tutorialspoint.com/fsharp/index.htm"
C#Page:Title:"LearnC#"
URL:"www.tutorialspoint.com/csharp/index.htm"

Example2
typestudent=
{Name:string;
ID:int;
RegistrationText:string;
IsRegistered:bool}
letgetStudentnameid=
{Name=name;ID=id;RegistrationText=null;IsRegistered=false}
letregisterStudentst=
{stwith
RegistrationText="Registered";
IsRegistered=true}
letprintStudentmsgst=
printfn"%s:%A"msgst
letmain()=
letpreRegisteredStudent=getStudent"Zara"10
letpostRegisteredStudent=registerStudentpreRegisteredStudent
printStudent"BeforeRegistration:"preRegisteredStudent
printStudent"AfterRegistration:"postRegisteredStudent
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
BeforeRegistration::{Name="Zara";
ID=10;
RegistrationText=null;
IsRegistered=false;}
AfterRegistration::{Name="Zara";
ID=10;
RegistrationText="Registered";
IsRegistered=true;}

F#LISTS
InF#,alistisanordered,immutableseriesofelementsofthesametype.Itistosomeextentequivalent
toalinkedlistdatastructure.
TheF#module,Microsoft.FSharp.Collections.List,hasthecommonoperationsonlists.However
F#importsthismoduleautomaticallyandmakesitaccessibletoeveryF#application.

CreatingandInitializingaList
Followingarethevariouswaysofcreatinglists
Usinglistliterals.
Usingcons:: operator.
UsingtheList.initmethodofListmodule.
UsingsomesyntacticconstructscalledListComprehensions.

ListLiterals
Inthismethod,youjustspecifyasemicolondelimitedsequenceofvaluesinsquarebrackets.For
example:
letlist1=[1;2;3;4;5;6;7;8;9;10]

Thecons :: Operator
Withthismethod,youcanaddsomevaluesbyprependingorconsingittoanexistinglistusingthe::
operator.Forexample
letlist1=[1;2;3;4;5;6;7;8;9;10]

[]denotesanemptylist.

ListinitMethod
TheList.initmethodoftheListmoduleisoftenusedforcreatinglists.Thismethodhasthetype
valinit:int>(int>'T)>'Tlist

Thefirstargumentisthedesiredlengthofthenewlist,andthesecondargumentisaninitializer
function,whichgeneratesitemsinthelist.
Forexample,
letlist5=List.init5(funindex>(index,index*index,index*index*index))

Here,theindexfunctiongeneratesthelist.

ListComprehensions
Listcomprehensionsarespecialsyntacticconstructsusedforgeneratinglists.
F#listcomprehensionsyntaxcomesintwoformsrangesandgenerators.
Rangeshavetheconstructs[start..end]and[start..step..end]
Forexample,

letlist3=[1..10]

Generatorshavetheconstruct[forxincollectiondo...yieldexpr]
Forexample,
letlist6=[forain1..10doyield(a*a)]

Astheyieldkeywordpushesasinglevalueintoalist,thekeyword,yield!,pushesacollectionofvalues
intothelist.
Thefollowingfunctiondemonstratestheabovemethods

Example
(*usinglistliterals*)
letlist1=[1;2;3;4;5;6;7;8;9;10]
printfn"Thelist:%A"list1
(*usingconsoperator*)
letlist2=1::2::3::[]
printfn"Thelist:%A"list2
(*usingrangeconstructs*)
letlist3=[1..10]
printfn"Thelist:%A"list3
(*usingrangeconstructs*)
letlist4=['a'..'m']
printfn"Thelist:%A"list4
(*usinginitmethod*)
letlist5=List.init5(funindex>(index,index*index,index*index*index))
printfn"Thelist:%A"list5
(*usingyieldoperator*)
letlist6=[forain1..10doyield(a*a)]
printfn"Thelist:%A"list6
(*usingyieldoperator*)
letlist7=[forain1..100doifa%3=0&&a%5=0thenyielda]
printfn"Thelist:%A"list7
(*usingyield!operator*)
letlist8=[forain1..3doyield![a..a+3]]
printfn"Thelist:%A"list8

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thelist:[1;2;3;4;5;6;7;8;9;10]
Thelist:[1;2;3]
Thelist:[1;2;3;4;5;6;7;8;9;10]
Thelist:['a';'b';'c';'d';'e';'f';'g';'h';'i';'j';'k';'l';'m']
Thelist:[(0,0,0);(1,1,1);(2,4,8);(3,9,27);(4,16,64)]
Thelist:[1;4;9;16;25;36;49;64;81;100]

Thelist:[15;30;45;60;75;90]
Thelist:[1;2;3;4;2;3;4;5;3;4;5;6]

PropertiesofListDataType
Thefollowingtableshowsvariouspropertiesoflistdatatype

Property

Type

Description

Head

'T

Thefirstelement.

Empty

'Tlist

Astaticpropertythatreturnsanemptylistoftheappropriatetype.

IsEmpty

bool

trueifthelisthasnoelements.

Item

'T

Theelementatthespecifiedindexzero based.

Length

int

Thenumberofelements.

Tail

'Tlist

Thelistwithoutthefirstelement.

Thefollowingexampleshowstheuseoftheseproperties

Example
letlist1=[2;4;6;8;10;12;14;16]
//UseofProperties
printfn"list1.IsEmptyis%b"(list1.IsEmpty)
printfn"list1.Lengthis%d"(list1.Length)
printfn"list1.Headis%d"(list1.Head)
printfn"list1.Tail.Headis%d"(list1.Tail.Head)
printfn"list1.Tail.Tail.Headis%d"(list1.Tail.Tail.Head)
printfn"list1.Item(1)is%d"(list1.Item(1))

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
list1.IsEmptyisfalse
list1.Lengthis8
list1.Headis2
list1.Tail.Headis4
list1.Tail.Tail.Headis6
list1.Item(1)is4

BasicOperatorsonList
Thefollowingtableshowsthebasicoperationsonlistdatatype

Value

Description

append:'Tlist'Tlist'Tlist

Returnsanewlistthatcontainstheelementsofthe
firstlistfollowedbyelementsofthesecond.

average:'Tlist^T

Returnstheaverageoftheelementsinthelist.

averageBy: T U'Tlist^U

Returnstheaverageoftheelementsgeneratedby
applyingthefunctiontoeachelementofthelist.

choose: T Uoption'Tlist'Ulist

Appliesthegivenfunctiontoeachelementofthe
list.Returnsthelistcomprisedoftheresultsfor
eachelementwherethefunctionreturnsSome.

collect: T Ulist'Tlist'Ulist

Foreachelementofthelist,appliesthegiven
function.Concatenatesalltheresultsandreturn
thecombinedlist.

concat:seq<'Tlist>'Tlist

Returnsanewlistthatcontainstheelementsof
eachthelistsinorder.

empty:'Tlist

Returnsanemptylistofthegiventype.

exists: T bool'Tlistbool

Testsifanyelementofthelistsatisfiesthegiven
predicate.

exists2: T1 T2 bool'T1list'T2list
bool

Testsifanypairofcorrespondingelementsofthe
listssatisfiesthegivenpredicate.

filter: T bool'Tlist'Tlist

Returnsanewcollectioncontainingonlythe
elementsofthecollectionforwhichthegiven
predicatereturnstrue.

find: T bool'Tlist'T

Returnsthefirstelementforwhichthegiven
functionreturnstrue.

findIndex: T bool'Tlistint

Returnstheindexofthefirstelementinthelist
thatsatisfiesthegivenpredicate.

fold: State T State'State'Tlist


'State

Appliesafunctiontoeachelementofthecollection,
threadinganaccumulatorargumentthroughthe
computation.Thisfunctiontakesthesecond
argument,andappliesthefunctiontoitandthe
firstelementofthelist.Then,itpassesthisresult
intothefunctionalongwiththesecondelement,
andsoon.Finally,itreturnsthefinalresult.Ifthe
inputfunctionisfandtheelementsarei0...iN,

thenthisfunctioncomputesf. . . (fsi0i1...)iN.
fold2: State T1 T2 State'State
'T1list'T2list'State

Appliesafunctiontocorrespondingelementsof
twocollections,threadinganaccumulator
argumentthroughthecomputation.The
collectionsmusthaveidenticalsizes.Iftheinput
functionisfandtheelementsarei0...iNand
j0...jN,thenthisfunctioncomputesf. . . (fsi0j0...)
iNjN.

foldBack: T State State'Tlist


'State'State

Appliesafunctiontoeachelementofthecollection,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthe
elementsarei0...iNthencomputesfi0. . . (fiNs).

foldBack2: T1 T2 State State'T1


list'T2list'State'State

Appliesafunctiontocorrespondingelementsof
twocollections,threadinganaccumulator
argumentthroughthecomputation.The
collectionsmusthaveidenticalsizes.Iftheinput
functionisfandtheelementsarei0...iNand
j0...jN,thenthisfunctioncomputesfi0j0
. . . (fiNjNs).

forall: T bool'Tlistbool

Testsifallelementsofthecollectionsatisfythe
givenpredicate.

forall2: T1 T2 bool'T1list'T2list
bool

Testsifallcorrespondingelementsofthecollection
satisfythegivenpredicatepairwise.

head:'Tlist'T

Returnsthefirstelementofthelist.

init:intint T'Tlist

Createsalistbycallingthegivengeneratoroneach
index.

isEmpty:'Tlistbool

Returnstrueifthelistcontainsnoelements,false
otherwise.

iter: T unit'Tlistunit

Appliesthegivenfunctiontoeachelementofthe
collection.

iter2: T1 T2 unit'T1list'T2list
unit

Appliesthegivenfunctiontotwocollections
simultaneously.Thecollectionsmusthaveidentical
size.

iteri:int T unit'Tlistunit

Appliesthegivenfunctiontoeachelementofthe
collection.Theintegerpassedtothefunction

indicatestheindexofelement.
iteri2:int T1 T2 unit'T1list'T2
listunit

Appliesthegivenfunctiontotwocollections
simultaneously.Thecollectionsmusthaveidentical
size.Theintegerpassedtothefunctionindicates
theindexofelement.

length:'Tlistint

Returnsthelengthofthelist.

map: T U'Tlist'Ulist

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontoeachofthe
elementsofthecollection.

map2: T1 T2 U'T1list'T2list
'Ulist

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontothe
correspondingelementsofthetwocollections
pairwise.

map3: T1 T2 T3 U'T1list'T2
list'T3list'Ulist

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontothe
correspondingelementsofthethreecollections
simultaneously.

mapi:int T U'Tlist'Ulist

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontoeachofthe
elementsofthecollection.Theintegerindex
passedtothefunctionindicatestheindexfrom0of
elementbeingtransformed.

mapi2:int T1 T2 U'T1list'T2
list'Ulist

LikeList.mapi,butmappingcorresponding
elementsfromtwolistsofequallength.

max:'Tlist'T

Returnsthegreatestofallelementsofthelist,
comparedbyusingOperators.max.

maxBy: T U'Tlist'T

Returnsthegreatestofallelementsofthelist,
comparedbyusingOperators.maxonthefunction
result.

min:'Tlist'T

Returnsthelowestofallelementsofthelist,
comparedbyusingOperators.min.

minBy: T U'Tlist'T

Returnsthelowestofallelementsofthelist,
comparedbyusingOperators.minonthefunction
result

nth:'Tlistint'T

Indexesintothelist.Thefirstelementhasindex0.

ofArray:'T[]'Tlist

Createsalistfromthegivenarray.

ofSeq:seq<'T>'Tlist

Createsanewlistfromthegivenenumerable
object.

partition: T bool'Tlist*'Tlist

Splitsthecollectionintotwocollections,containing
theelementsforwhichthegivenpredicatereturns
trueandfalserespectively.

permute:int int'Tlist'Tlist

Returnsalistwithallelementspermutedaccording
tothespecifiedpermutation.

pick: T Uoption'Tlist'U

Appliesthegivenfunctiontosuccessiveelements,
returningthefirstresultwherefunctionreturns
Someforsomevalue.

reduce: T T T'Tlist'T

Appliesafunctiontoeachelementofthecollection,
threadinganaccumulatorargumentthroughthe
computation.Thisfunctionappliesthespecified
functiontothefirsttwoelementsofthelist.Itthen
passesthisresultintothefunctionalongwiththe
thirdelement,andsoon.Finally,itreturnsthe
finalresult.Iftheinputfunctionisfandthe
elementsarei0...iN,thenthisfunctioncomputesf
. . . (fi0i1i2...)iN.

reduceBack: T T T'Tlist'T

Appliesafunctiontoeachelementofthecollection,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthe
elementsarei0...iN,thenthisfunctioncomputesf
i0. . . (fiN 1iN).

replicate:int T Tlist

Createsalistbycallingthegivengeneratoroneach
index.

rev:'Tlist'Tlist

Returnsanewlistwiththeelementsinreverse
order.

scan: State T State'State'Tlist


'Statelist

Appliesafunctiontoeachelementofthecollection,
threadinganaccumulatorargumentthroughthe
computation.Thisfunctiontakesthesecond
argument,andappliesthespecifiedfunctiontoit
andthefirstelementofthelist.Then,itpassesthis
resultintothefunctionalongwiththesecond

elementandsoon.Finally,itreturnsthelistof
intermediateresultsandthefinalresult.
scanBack: T State State'Tlist
'State'Statelist

LikefoldBack,butreturnsboththeintermediate
andfinalresults

sort:'Tlist'Tlist

SortsthegivenlistusingOperators.compare.

sortBy: T Key'Tlist'Tlist

Sortsthegivenlistusingkeysgivenbythegiven
projection.Keysarecomparedusing
Operators.compare.

sortWith: T T int'Tlist'Tlist

Sortsthegivenlistusingthegivencomparison
function.

sum:^Tlist^T

Returnsthesumoftheelementsinthelist.

sumBy: T U'Tlist^U

Returnsthesumoftheresultsgeneratedby
applyingthefunctiontoeachelementofthelist.

tail:'Tlist'Tlist

Returnstheinputlistwithoutthefirstelement.

toArray:'Tlist'T[]

Createsanarrayfromthegivenlist.

toSeq:'Tlistseq<'T>

Viewsthegivenlistasasequence.

tryFind: T bool'Tlist'Toption

Returnsthefirstelementforwhichthegiven
functionreturnstrue.ReturnNoneifnosuch
elementexists.

tryFindIndex: T bool'Tlistintoption

Returnstheindexofthefirstelementinthelist
thatsatisfiesthegivenpredicate.ReturnNoneif
nosuchelementexists.

tryPick: T Uoption'Tlist'Uoption

Appliesthegivenfunctiontosuccessiveelements,
returningthefirstresultwherefunctionreturns
Someforsomevalue.Ifnosuchelementexists
thenreturnNone.

unzip: T1 T2list'T1list*'T2list

Splitsalistofpairsintotwolists.

unzip3: T1 T2 T3list'T1list*'T2list
*'T3list

Splitsalistoftriplesintothreelists.

zip:'T1list'T2list T1 T2list

Combinesthetwolistsintoalistofpairs.Thetwo
listsmusthaveequallengths.

zip3:'T1list'T2list'T3list
T1 T2 T3list

Combinesthethreelistsintoalistoftriples.The
listsmusthaveequallengths.

Thefollowingexamplesdemonstratetheusesoftheabovefunctionalities

Example1
Thisprogramshowsreversingalistrecursively
letlist1=[2;4;6;8;10;12;14;16]
printfn"Theoriginallist:%A"list1
letreverselt=
letrecloopacc=function
|[]>acc
|hd::tl>loop(hd::acc)tl
loop[]lt

printfn"Thereversedlist:%A"(reverselist1)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Theoriginallist:[2;4;6;8;10;12;14;16]
Thereversedlist:[16;14;12;10;8;6;4;2]

However,youcanusetherevfunctionofthemoduleforthesamepurpose
letlist1=[2;4;6;8;10;12;14;16]
printfn"Theoriginallist:%A"list1
printfn"Thereversedlist:%A"(List.revlist1)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Theoriginallist:[2;4;6;8;10;12;14;16]
Thereversedlist:[16;14;12;10;8;6;4;2]

Example2
ThisprogramshowsfilteringalistusingtheList.filtermethod
letlist1=[1;2;3;4;5;6;7;8;9;10]
printfn"Thelist:%A"list1
letlist2=list1|>List.filter(funx>x%2=0);;
printfn"TheFilteredlist:%A"list2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thelist:[1;2;3;4;5;6;7;8;9;10]
TheFilteredlist:[2;4;6;8;10]

Example3
TheList.mapmethodmapsalistfromonetypetoanother
letlist1=[1;2;3;4;5;6;7;8;9;10]
printfn"Thelist:%A"list1
letlist2=list1|>List.map(funx>(x*x).ToString());;
printfn"TheMappedlist:%A"list2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thelist:[1;2;3;4;5;6;7;8;9;10]
TheMappedlist:["1";"4";"9";"16";"25";"36";"49";"64";"81";"100"]

Example4
TheList.appendmethodandthe@operatorappendsonelisttoanother
letlist1=[1;2;3;4;5]
letlist2=[6;7;8;9;10]
letlist3=List.appendlist1list2
printfn"Thefirstlist:%A"list1
printfn"Thesecondlist:%A"list2
printfn"Theappenedlist:%A"list3
letlt1=['a';'b';'c']
letlt2=['e';'f';'g']
letlt3=lt1@lt2
printfn"Thefirstlist:%A"lt1
printfn"Thesecondlist:%A"lt2
printfn"Theappenedlist:%A"lt3

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thefirstlist:[1;2;3;4;5]
Thesecondlist:[6;7;8;9;10]
Theappenedlist:[1;2;3;4;5;6;7;8;9;10]
Thefirstlist:['a';'b';'c']
Thesecondlist:['e';'f';'g']
Theappenedlist:['a';'b';'c';'e';'f';'g']

Example5
TheList.sortmethodsortsalist.TheList.summethodgivesthesumofelementsinthelistandthe
List.averagemethodgivestheaverageofelementsinthelist
letlist1=[9.0;0.0;2.0;4.5;11.2;8.0;10.0]
printfn"Thelist:%A"list1
letlist2=List.sortlist1
printfn"Thesortedlist:%A"list2

lets=List.sumlist1
letavg=List.averagelist1
printfn"Thesum:%f"s
printfn"Theaverage:%f"avg

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thelist:[9.0;0.0;2.0;4.5;11.2;8.0;10.0]
Thesortedlist:[10.0;4.5;0.0;2.0;8.0;9.0;11.2]
Thesum:15.700000
Theaverage:2.242857

A"fold"operationappliesafunctiontoeachelementinalist,aggregatestheresultofthefunctioninan
accumulatorvariable,andreturnstheaccumulatorastheresultofthefoldoperation.

Example6
TheList.foldmethodappliesafunctiontoeachelementfromlefttoright,whileList.foldBack
appliesafunctiontoeachelementfromrighttoleft.
letsumListlist=List.fold(funaccelem>acc+elem)0list
printfn"Sumoftheelementsoflist%Ais%d."[1..10](sumList[1..10])

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Sumoftheelementsoflist[1;2;3;4;5;6;7;8;9;10]is55.

F#SEQUENCES
Sequences,likelistsalsorepresentanorderedcollectionofvalues.However,theelementsinasequence
orsequenceexpressionarecomputedwhenrequired.Theyarenotcomputedatonce,andforthis
reasontheyareusedtorepresentinfinitedatastructures.

DefiningSequences
Sequencesaredefinedusingthefollowingsyntax
seq{expr}

Forexample,
letseq1=seq{1..10}

CreatingSequencesandSequencesExpressions
Similartolists,youcancreatesequencesusingrangesandcomprehensions.
Sequenceexpressionsaretheexpressionsyoucanwriteforcreatingsequences.Thesecanbedone
Byspecifyingtherange.
Byspecifyingtherangewithincrementordecrement.

Byusingtheyieldkeywordtoproducevaluesthatbecomepartofthesequence.
Byusingtheoperator.
Thefollowingexamplesdemonstratetheconcept

Example1
(*Sequences*)
letseq1=seq{1..10}
(*ascendingorderandincrement*)
printfn"TheSequence:%A"seq1
letseq2=seq{1..5..50}
(*descendingorderanddecrement*)
printfn"TheSequence:%A"seq2
letseq3=seq{50..5..0}
printfn"TheSequence:%A"seq3
(*usingyield*)
letseq4=seq{forain1..10doyielda,a*a,a*a*a}
printfn"TheSequence:%A"seq4

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
TheSequence:seq[1;2;3;4;...]
TheSequence:seq[1;6;11;16;...]
TheSequence:seq[50;45;40;35;...]
TheSequence:seq[(1,1,1);(2,4,8);(3,9,27);(4,16,64);...]

Example2
Thefollowingprogramprintstheprimenumbersfrom1to50
(*Recursiveisprimefunction.*)
letisprimen=
letrecchecki=
i>n/2||(n%i<>0&&check(i+1))
check2
letprimeIn50=seq{fornin1..50doifisprimenthenyieldn}
forxinprimeIn50do
printfn"%d"x

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
1
2
3
5
7
11
13
17

19
23
29
31
37
41
43
47

BasicOperationsonSequence
Thefollowingtableshowsthebasicoperationsonsequencedatatype

Value

Description

append:seq<'T>seq<'T>seq<'T>

Wrapsthetwogivenenumerationsasasingle
concatenatedenumeration.

average:seq<^T>^T

Returnstheaverageoftheelementsinthe
sequence.

averageBy: T Useq<'T>^U

Returnstheaverageoftheresultsgeneratedby
applyingthefunctiontoeachelementofthe
sequence.

cache:seq<'T>seq<'T>

Returnsasequencethatcorrespondstoacached
versionoftheinputsequence.

cast:IEnumerableseq<'T>

WrapsalooselytypedSystem.Collections
sequenceasatypedsequence.

choose: T Uoptionseq<'T>seq<'U>

Appliesthegivenfunctiontoeachelementofthe
list.Returnthelistcomprisedoftheresultsfor
eachelementwherethefunctionreturnsSome.

collect: T Collectionseq<'T>
seq<'U>

Appliesthegivenfunctiontoeachelementofthe
sequenceandconcatenatesalltheresults.

compareWith: T T intseq<'T>
seq<'T>int

Comparestwosequencesusingthegiven
comparisonfunction,elementbyelement.

concat:seq<'Collection>seq<'T>

Combinesthegivenenumerationofenumerations
asasingleconcatenatedenumeration.

countBy: T Keyseq<'T>seq<'Key*
int>

Appliesakeygeneratingfunctiontoeachelement
ofasequenceandreturnasequenceyielding
uniquekeysandtheirnumberofoccurrencesinthe
originalsequence.

delay:unit seq < T > seq<'T>

Returnsasequencethatisbuiltfromthegiven
delayedspecificationofasequence.

distinct:seq<'T>seq<'T>

Returnsasequencethatcontainsnoduplicate
entriesaccordingtogenerichashandequality
comparisonsontheentries.Ifanelementoccurs
multipletimesinthesequencethenthelater
occurrencesarediscarded.

distinctBy: T Keyseq<'T>seq<'T>

Returnsasequencethatcontainsnoduplicate
entriesaccordingtothegenerichashandequality
comparisonsonthekeysreturnedbythegivenkey
generatingfunction.Ifanelementoccursmultiple
timesinthesequencethenthelateroccurrences
arediscarded.

empty:seq<'T>

Createsanemptysequence.

exactlyOne:seq<'T>'T

Returnstheonlyelementofthesequence.

exists: T boolseq<'T>bool

Testsifanyelementofthesequencesatisfiesthe
givenpredicate.

exists2: T1 T2 boolseq<'T1>
seq<'T2>bool

Testsifanypairofcorrespondingelementsofthe
inputsequencessatisfiesthegivenpredicate.

filter: T boolseq<'T>seq<'T>

Returnsanewcollectioncontainingonlythe
elementsofthecollectionforwhichthegiven
predicatereturnstrue.

find: T boolseq<'T>'T

Returnsthefirstelementforwhichthegiven
functionreturnstrue.

findIndex: T boolseq<'T>int

Returnstheindexofthefirstelementforwhichthe
givenfunctionreturnstrue.

fold: State T State'Stateseq<'T>


'State

Appliesafunctiontoeachelementofthecollection,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthe
elementsarei0...iN,thenthisfunctioncomputesf
. . . (fsi0...)iN.

forall: T boolseq<'T>bool

Testsifallelementsofthesequencesatisfythe
givenpredicate.

forall2: T1 T2 boolseq<'T1>
seq<'T2>bool

Teststheallpairsofelementsdrawnfromthetwo
sequencessatisfythegivenpredicate.Ifone
sequenceisshorterthantheotherthenthe
remainingelementsofthelongersequenceare
ignored.

groupBy: T Keyseq<'T>seq<'Key*
seq<'T>>

Appliesakeygeneratingfunctiontoeachelement
ofasequenceandyieldsasequenceofuniquekeys.
Eachuniquekeyhasalsocontainsasequenceofall
elementsthatmatchtothiskey.

head:seq<'T>'T

Returnsthefirstelementofthesequence.

init:intint Tseq<'T>

Generatesanewsequencewhich,wheniterated,
returnssuccessiveelementsbycallingthegiven
function,uptothegivencount.Theresultsof
callingthefunctionarenotsaved,thatis,the
functionisreappliedasnecessarytoregeneratethe
elements.Thefunctionispassedtheindexofthe
itembeinggenerated.

initInfinite:int Tseq<'T>

Generatesanewsequencewhich,wheniterated,
willreturnsuccessiveelementsbycallingthegiven
function.Theresultsofcallingthefunctionarenot
saved,thatis,thefunctionwillbereappliedas
necessarytoregeneratetheelements.Thefunction
ispassedtheindexoftheitembeinggenerated.

isEmpty:seq<'T>bool

Testswhetherasequencehasanyelements.

iter: T unitseq<'T>unit

Appliesthegivenfunctiontoeachelementofthe
collection.

iter2: T1 T2 unitseq<'T1>
seq<'T2>unit

Appliesthegivenfunctiontotwocollections
simultaneously.Ifonesequenceisshorterthanthe
otherthentheremainingelementsofthelonger
sequenceareignored.

iteri:int T unitseq<'T>unit

Appliesthegivenfunctiontoeachelementofthe
collection.Theintegerpassedtothefunction
indicatestheindexofelement.

last:seq<'T>'T

Returnsthelastelementofthesequence.

length:seq<'T>int

Returnsthelengthofthesequence.

map: T Useq<'T>seq<'U>

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontoeachofthe
elementsofthecollection.Thegivenfunctionwill
beappliedaselementsaredemandedusingthe
MoveNextmethodonenumeratorsretrievedfrom
theobject.

map2: T1 T2 Useq<'T1>
seq<'T2>seq<'U>

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontothe
correspondingpairsofelementsfromthetwo
sequences.Ifoneinputsequenceisshorterthan
theotherthentheremainingelementsofthe
longersequenceareignored.

mapi:int T Useq<'T>seq<'U>

Createsanewcollectionwhoseelementsarethe
resultsofapplyingthegivenfunctiontoeachofthe
elementsofthecollection.Theintegerindex
passedtothefunctionindicatestheindexfrom0of
elementbeingtransformed.

max:seq<'T>'T

Returnsthegreatestofallelementsofthe
sequence,comparedbyusingOperators.max.

maxBy: T Useq<'T>'T

Returnsthegreatestofallelementsofthe
sequence,comparedbyusingOperators.maxon
thefunctionresult.

min:seq<'T>'T

Returnsthelowestofallelementsofthesequence,
comparedbyusingOperators.min.

minBy: T Useq<'T>'T

Returnsthelowestofallelementsofthesequence,
comparedbyusingOperators.minonthefunction
result.

nth:intseq<'T>'T

Computesthenthelementinthecollection.

ofArray:'Tarrayseq<'T>

Viewsthegivenarrayasasequence.

ofList:'Tlistseq<'T>

Viewsthegivenlistasasequence.

pairwise:seq<'T>seq<'T*'T>

Returnsasequenceofeachelementintheinput
sequenceanditspredecessor,withtheexceptionof
thefirstelementwhichisonlyreturnedasthe
predecessorofthesecondelement.

pick: T Uoptionseq<'T>'U

Appliesthegivenfunctiontosuccessiveelements,
returningthefirstvaluewherethefunctionreturns
aSomevalue.

readonly:seq<'T>seq<'T>

Createsanewsequenceobjectthatdelegatestothe
givensequenceobject.Thisensurestheoriginal
sequencecannotberediscoveredandmutatedbya
typecast.Forexample,ifgivenanarraythe
returnedsequencewillreturntheelementsofthe
array,butyoucannotcastthereturnedsequence
objecttoanarray.

reduce: T T Tseq<'T>'T

Appliesafunctiontoeachelementofthesequence,
threadinganaccumulatorargumentthroughthe
computation.Beginbyapplyingthefunctiontothe
firsttwoelements.Thenfeedthisresultintothe
functionalongwiththethirdelementandsoon.
Returnthefinalresult.

scan: State T State'Stateseq<'T>


seq<'State>

LikeSeq.fold,butcomputesondemandand
returnsthesequenceofintermediaryandfinal
results.

singleton:'Tseq<'T>

Returnsasequencethatyieldsoneitemonly.

skip:intseq<'T>seq<'T>

Returnsasequencethatskipsaspecifiednumber
ofelementsoftheunderlyingsequenceandthen
yieldstheremainingelementsofthesequence.

skipWhile: T boolseq<'T>seq<'T>

Returnsasequencethat,wheniterated,skips
elementsoftheunderlyingsequencewhilethe
givenpredicatereturnstrue,andthenyieldsthe
remainingelementsofthesequence.

sort:seq<'T>seq<'T>

Yieldsasequenceorderedbykeys.

sortBy: T Keyseq<'T>seq<'T>

Appliesakeygeneratingfunctiontoeachelement
ofasequenceandyieldasequenceorderedbykeys.
Thekeysarecomparedusinggenericcomparison
asimplementedbyOperators.compare.

sum:seq<^T>^T

Returnsthesumoftheelementsinthesequence.

sumBy

Returnsthesumoftheresultsgeneratedby
applyingthefunctiontoeachelementofthe
sequence.

take:intseq<'T>seq<'T>

Returnsthefirstelementsofthesequenceuptoa
specifiedcount.

takeWhile: T boolseq<'T>seq<'T>

Returnsasequencethat,wheniterated,yields
elementsoftheunderlyingsequencewhilethe
givenpredicatereturnstrue,andthenreturnsno
furtherelements.

toArray:seq<'T>'T[]

Createsanarrayfromthegivencollection.

toList:seq<'T>'Tlist

Createsalistfromthegivencollection.

truncate:intseq<'T>seq<'T>

Returnsasequencethatwhenenumeratedreturns
nomorethanaspecifiednumberofelements.

tryFind: T boolseq<'T>'Toption

Returnsthefirstelementforwhichthegiven
functionreturnstrue,orNoneifnosuchelement
exists.

tryFindIndex: T boolseq<'T>int
option

Returnstheindexofthefirstelementinthe
sequencethatsatisfiesthegivenpredicate,or
Noneifnosuchelementexists.

tryPick: T Uoptionseq<'T>'Uoption

Appliesthegivenfunctiontosuccessiveelements,
returningthefirstvaluewherethefunctionreturns
aSomevalue.

unfold: State T Stateoption'State


seq<'T>

Returnsasequencethatcontainstheelements
generatedbythegivencomputation.

where: T boolseq<'T>seq<'T>

Returnsanewcollectioncontainingonlythe
elementsofthecollectionforwhichthegiven
predicatereturnstrue.AsynonymforSeq.filter.

windowed:intseq<'T>seq<'T[]>

Returnsasequencethatyieldsslidingwindowsof
containingelementsdrawnfromtheinput
sequence.Eachwindowisreturnedasafresharray.

zip:seq<'T1>seq<'T2>seq<'T1*'T2>

Combinesthetwosequencesintoalistofpairs.
Thetwosequencesneednothaveequallengths
whenonesequenceisexhaustedanyremaining
elementsintheothersequenceareignored.

zip3:seq<'T1>seq<'T2>seq<'T3>
seq<'T1*'T2*'T3>

Combinesthethreesequencesintoalistoftriples.
Thesequencesneednothaveequallengthswhen

onesequenceisexhaustedanyremainingelements
intheothersequencesareignored.

Thefollowingexamplesdemonstratetheusesofsomeoftheabovefunctionalities

Example1
Thisprogramcreatesanemptysequenceandfillsituplater
(*Creatingsequences*)
letemptySeq=Seq.empty
letseq1=Seq.singleton20
printfn"Thesingletonsequence:"
printfn"%A"seq1
printfn"Theinitsequence:"
letseq2=Seq.init5(funn>n*3)
Seq.iter(funi>printf"%d"i)seq2
printfn""
(*convertinganarraytosequencebyusingcast*)
printfn"Thearraysequence1:"
letseq3=[|1..10|]:>seq<int>
Seq.iter(funi>printf"%d"i)seq3
printfn""
(*convertinganarraytosequencebyusingSeq.ofArray*)
printfn"Thearraysequence2:"
letseq4=[|2..2..20|]|>Seq.ofArray
Seq.iter(funi>printf"%d"i)seq4
printfn""

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thesingletonsequence:
seq[20]
Theinitsequence:
036912
Thearraysequence1:
12345678910
Thearraysequence2:
2468101214161820

Pleasenotethat
TheSeq.emptymethodcreatesanemptysequence.
TheSeq.singletonmethodcreatesasequenceofjustonespecifiedelement.
TheSeq.initmethodcreatesasequenceforwhichtheelementsarecreatedbyusingagiven
function.
TheSeq.ofArrayandSeq.ofList<'T>methodscreatesequencesfromarraysandlists.

TheSeq.itermethodallowsiteratingthroughasequence.

Example2
TheSeq.unfoldmethodgeneratesasequencefromacomputationfunctionthattakesastateand
transformsittoproduceeachsubsequentelementinthesequence.
Thefollowingfunctionproducesthefirst20naturalnumbers
letseq1=Seq.unfold(funstate>if(state>20)thenNoneelseSome(state,state+
1))0
printfn"Thesequenceseq1containsnumbersfrom0to20."
forxinseq1doprintf"%d"x
printfn""

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thesequenceseq1containsnumbersfrom0to20.
01234567891011121314151617181920

Example3
TheSeq.truncatemethodcreatesasequencefromanothersequence,butlimitsthesequencetoa
specifiednumberofelements.
TheSeq.takemethodcreatesanewsequencethatcontainsaspecifiednumberofelementsfromthestart
ofasequence.
letmySeq=seq{foriin1..10>3*i}
lettruncatedSeq=Seq.truncate5mySeq
lettakeSeq=Seq.take5mySeq
printfn"Theoriginalsequence"
Seq.iter(funi>printf"%d"i)mySeq
printfn""
printfn"Thetruncatedsequence"
Seq.iter(funi>printf"%d"i)truncatedSeq
printfn""
printfn"Thetakesequence"
Seq.iter(funi>printf"%d"i)takeSeq
printfn""

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Theoriginalsequence
36912151821242730
Thetruncatedsequence
3691215
Thetakesequence
3691215

F#SETS

AsetinF#isadatastructurethatactsasacollectionofitemswithoutpreservingtheorderinwhich
itemsareinserted.Setsdonotallowduplicateentriestobeinsertedintothecollection.

CreatingSets
Setscanbecreatedinthefollowingways
BycreatinganemptysetusingSet.emptyandaddingitemsusingtheaddfunction.
Convertingsequencesandliststosets.
Thefollowingprogramdemonstratesthetechniques
(*creatingsets*)
letset1=Set.empty.Add(3).Add(5).Add(7).Add(9)
printfn"Thenewset:%A"set1
letweekdays=Set.ofList["mon";"tues";"wed";"thurs";"fri"]
printfn"Thelistset:%A"weekdays
letset2=Set.ofSeq[1..2..10]
printfn"Thesequenceset:%A"set2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thenewset:set[3;5;7;9]
Thelistset:set["fri";"mon";"thurs";"tues";"wed"]
Thesequenceset:set[1;3;5;7;9]

BasicOperationsonSets
Thefollowingtableshowsthebasicoperationsonsets

Value

Description

add:'TSet<'T>Set<'T>

Returnsanewsetwithanelementaddedtotheset.
Noexceptionisraisedifthesetalreadycontains
thegivenelement.

contains:'TSet<'T>bool

Evaluatestotrueifthegivenelementisinthe
givenset.

count:Set<'T>int

Returnsthenumberofelementsintheset.

difference:Set<'T>Set<'T>Set<'T>

Returnsanewsetwiththeelementsofthesecond
setremovedfromthefirst.

empty:Set<'T>

Theemptysetforthespecifiedtype.

exists: T boolSet<'T>bool

Testsifanyelementofthecollectionsatisfiesthe
givenpredicate.Iftheinputfunctionispredicate

andtheelementsarei0...iN,thenthisfunction
computespredicatei0or...orpredicateiN.
filter: T boolSet<'T>Set<'T>

Returnsanewcollectioncontainingonlythe
elementsofthecollectionforwhichthegiven
predicatereturnstrue.

fold: State T State'StateSet<'T>


'State

Appliesthegivenaccumulatingfunctiontoallthe
elementsoftheset.

foldBack: T State StateSet<'T>


'State'State

Appliesthegivenaccumulatingfunctiontoallthe
elementsoftheset.

forall: T boolSet<'T>bool

Testsifallelementsofthecollectionsatisfythe
givenpredicate.Iftheinputfunctionispandthe
elementsarei0...iN,thenthisfunctioncomputesp
i0&&...&&piN.

intersect:Set<'T>Set<'T>Set<'T>

Computestheintersectionofthetwosets.

intersectMany:seq<Set<'T>>Set<'T>

Computestheintersectionofasequenceofsets.
Thesequencemustbenonempty.

isEmpty:Set<'T>bool

Returnstrueifthesetisempty.

isProperSubset:Set<'T>Set<'T>bool

Evaluatestotrueifallelementsofthefirstsetare
inthesecond,andatleastoneelementofthe
secondisnotinthefirst.

isProperSuperset:Set<'T>Set<'T>bool

Evaluatestotrueifallelementsofthesecondset
areinthefirst,andatleastoneelementofthefirst
isnotinthesecond.

isSubset:Set<'T>Set<'T>bool

Evaluatestotrueifallelementsofthefirstsetare
inthesecond.

isSuperset:Set<'T>Set<'T>bool

Evaluatestotrueifallelementsofthesecondset
areinthefirst.

iter: T unitSet<'T>unit

Appliesthegivenfunctiontoeachelementofthe
set,inorderaccordingtothecomparisonfunction.

map: T USet<'T>Set<'U>

Returnsanewcollectioncontainingtheresultsof
applyingthegivenfunctiontoeachelementofthe
inputset.

maxElement:Set<'T>'T

Returnsthehighestelementinthesetaccordingto

theorderingbeingusedfortheset.
minElement:Set<'T>'T

Returnsthelowestelementinthesetaccordingto
theorderingbeingusedfortheset.

ofArray:'TarraySet<'T>

Createsasetthatcontainsthesameelementsasthe
givenarray.

ofList:'TlistSet<'T>

Createsasetthatcontainsthesameelementsasthe
givenlist.

ofSeq:seq<'T>Set<'T>

Createsanewcollectionfromthegiven
enumerableobject.

partition: T boolSet<'T>Set<'T>*
Set<'T>

Splitsthesetintotwosetscontainingtheelements
forwhichthegivenpredicatereturnstrueandfalse
respectively.

remove:'TSet<'T>Set<'T>

Returnsanewsetwiththegivenelementremoved.
Noexceptionisraisedifthesetdoesn'tcontainthe
givenelement.

singleton:'TSet<'T>

Thesetcontainingthegivenelement.

toArray:Set<'T>'Tarray

Createsanarraythatcontainstheelementsofthe
setinorder.

toList:Set<'T>'Tlist

Createsalistthatcontainstheelementsoftheset
inorder.

toSeq:Set<'T>seq<'T>

Returnsanorderedviewofthecollectionasan
enumerableobject.

union:Set<'T>Set<'T>Set<'T>

Computestheunionofthetwosets.

unionMany:seq<Set<'T>>Set<'T>

Computestheunionofasequenceofsets.

Thefollowingexampledemonstratestheusesofsomeoftheabovefunctionalities

Example
leta=Set.ofSeq[1..2..20]
letb=Set.ofSeq[1..3..20]
letc=Set.intersectab
letd=Set.unionab
lete=Set.differenceab
printfn"Seta:"

Set.iter(funx>printf"%O"x)a
printfn""
printfn"Setb:"
Set.iter(funx>printf"%O"x)b
printfn""
printfn"Setc=setintersectofaandb:"
Set.iter(funx>printf"%O"x)c
printfn""
printfn"Setd=setunionofaandb:"
Set.iter(funx>printf"%O"x)d
printfn""
printfn"Sete=setdifferenceofaandb:"
Set.iter(funx>printf"%O"x)e
printfn""

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Seta:
135791113151719
Setb:
14710131619
Setc=setintersectofaandb:
171319
Setd=setunionofaandb:
13457910111315161719
Sete=setdifferenceofaandb:
359111517

F#MAPS
InF#,amapisaspecialkindofsetthatassociatesthevalueswithkey.Amapiscreatedinasimilarway
assetsarecreated.

CreatingMaps
MapsarecreatedbycreatinganemptymapusingMap.emptyandaddingitemsusingtheAddfunction.
Thefollowingexampledemonstratesthis

Example
(*CreateanemptyMap*)
letstudents=
Map.empty.(*CreatinganemptyMap*)
Add("ZaraAli","1501").
Add("RishitaGupta","1502").
Add("RobinSahoo","1503").
Add("GillianMegan","1504");;
printfn"Mapstudents:%A"students
(*ConvertalisttoMap*)
letcapitals=
["Argentina","BuenosAires";

"France","Paris";
"Chili","Santiago";
"Malaysia","KualaLumpur";
"Switzerland","Bern"]
|>Map.ofList;;
printfn"Mapcapitals:%A"capitals

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Mapstudents:map
[("GillianMegan","1504");("RishitaGupta","1502");("RobinSahoo","1503
");
("ZaraAli","1501")]
Mapcapitals:map
[("Argentina","BuenosAires");("Chili","Santiago");("France","Paris");
("Malaysia","KualaLumpur");("Switzerland","Bern")]

Youcanaccessindividualelementsinthemapusingthekey.

Example
(*CreateanemptyMap*)
letstudents=
Map.empty.(*CreatinganemptyMap*)
Add("ZaraAli","1501").
Add("RishitaGupta","1502").
Add("RobinSahoo","1503").
Add("GillianMegan","1504");;
printfn"Mapstudents:%A"students
(*Accessinganelementusingkey*)
printfn"%A"students.["ZaraAli"]

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Mapstudents:map
[("GillianMegan","1504");("RishitaGupta","1502");("RobinSahoo","1503
");
("ZaraAli","1501")]
"1501"

BasicOperationsonMaps
Addmodulename
Thefollowingtableshowsthebasicoperationsonmaps

Member

Description

Add

Returnsanewmapwiththebindingaddedtothegivenmap.

ContainsKey

Testsifanelementisinthedomainofthemap.

Count

Thenumberofbindingsinthemap.

IsEmpty

Returnstrueiftherearenobindingsinthemap.

Item

Lookupanelementinthemap.RaisesKeyNotFoundExceptionifnobindingexistsin
themap.

Remove

Removesanelementfromthedomainofthemap.Noexceptionisraisedifthe
elementisnotpresent.

TryFind

Lookupanelementinthemap,returningaSomevalueiftheelementisinthe
domainofthemapandNoneifnot.

Thefollowingexampledemonstratestheusesofsomeoftheabovefunctionalities

Example
(*CreateanemptyMap*)
letstudents=
Map.empty.(*CreatinganemptyMap*)
Add("ZaraAli","1501").
Add("RishitaGupta","1502").
Add("RobinSahoo","1503").
Add("GillianMegan","1504").
Add("ShraddhaDubey","1505").
Add("NovonilSarker","1506").
Add("JoanPaul","1507");;
printfn"Mapstudents:%A"students
printfn"Mapnumberofstudents:%d"students.Count
(*findingtheregistrationnumberofastudent*)
letfound=students.TryFind"RishitaGupta"
matchfoundwith
|Somex>printfn"Found%s."x
|None>printfn"Didnotfindthespecifiedvalue."

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Mapstudents:map
[("GillianMegan","1504");("JoanPaul","1507");("NovonilSarker","1506"
);
("RishitaGupta","1502");("RobinSahoo","1503");
("ShraddhaDubey","1505");("ZaraAli","1501")]
Mapnumberofstudents:7
Found1502.

F#DISCRIMINATEDUNIONS
Unions,ordiscriminatedunionsallowsyoutobuildupcomplexdatastructuresrepresentingwell
definedsetofchoices.Forexample,youneedtobuildanimplementationofachoicevariable,whichhas
twovaluesyesandno.UsingtheUnionstool,youcandesignthis.

Syntax
Discriminatedunionsaredefinedusingthefollowingsyntax
typetypename=
|caseidentifier1[of[fieldname1:]type1[*[fieldname2:]
type2...]
|caseidentifier2[of[fieldname3:]type3[*[fieldname4:]type4...]
...

Oursimpleimplementationof,choice,willlooklikethefollowing
typechoice=
|Yes
|No

Thefollowingexampleusesthetypechoice
typechoice=
|Yes
|No
letx=Yes(*createsaninstanceofchoice*)
lety=No(*createsanotherinstanceofchoice*)
letmain()=
printfn"x:%A"x
printfn"y:%A"y
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
x:Yes
y:No

Example1
Thefollowingexampleshowstheimplementationofthevoltagestatesthatsetsabitonhighorlow
typeVoltageState=
|High
|Low
lettoggleSwitch=function(*patternmatchinginput*)
|High>Low
|Low>High
letmain()=
leton=High
letoff=Low
letchange=toggleSwitchoff
printfn"Switchonstate:%A"on
printfn"Switchoffstate:%A"off
printfn"Toggleoff:%A"change

printfn"ToggletheChangedstate:%A"(toggleSwitchchange)
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Switchonstate:High
Switchoffstate:Low
Toggleoff:High
ToggletheChangedstate:Low

Example2
typeShape=
//herewestoretheradiusofacircle
|Circleoffloat
//herewestorethesidelength.
|Squareoffloat
//herewestoretheheightandwidth.
|Rectangleoffloat*float
letpi=3.141592654
letareamyShape=
matchmyShapewith
|Circleradius>pi*radius*radius
|Squares>s*s
|Rectangle(h,w)>h*w
letradius=12.0
letmyCircle=Circle(radius)
printfn"Areaofcirclewithradius%g:%g"radius(areamyCircle)
letside=15.0
letmySquare=Square(side)
printfn"Areaofsquarethathasside%g:%g"side(areamySquare)
letheight,width=5.0,8.0
letmyRectangle=Rectangle(height,width)
printfn"Areaofrectanglewithheight%gandwidth%gis%g"heightwidth(area
myRectangle)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Areaofcirclewithradius12:452.389
Areaofsquarethathasside15:225
Areaofrectanglewithheight5andwidth8is40

F#MUTABLEDATA
VariablesinF#areimmutable,whichmeansonceavariableisboundtoavalue,itcantbechanged.
Theyareactuallycompiledasstaticreadonlyproperties.

Thefollowingexampledemonstratesthis.

Example
letx=10
lety=20
letz=x+y
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z
letx=15
lety=20
letz=x+y
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z

Whenyoucompileandexecutetheprogram,itshowsthefollowingerrormessage
Duplicatedefinitionofvalue'x'
Duplicatedefinitionofvalue'Y'
Duplicatedefinitionofvalue'Z'

MutableVariables
Attimesyouneedtochangethevaluesstoredinavariable.Tospecifythattherecouldbeachangeinthe
valueofadeclaredandassignedvariableinlaterpartofaprogram,F#providesthemutablekeyword.
Youcandeclareandassignmutablevariablesusingthiskeyword,whosevaluesyouwillchange.
Themutablekeywordallowsyoutodeclareandassignvaluesinamutablevariable.
Youcanassignsomeinitialvaluetoamutablevariableusingtheletkeyword.However,toassignnew
subsequentvaluetoit,youneedtousethe<operator.
Forexample,
letmutablex=10
x<15

Thefollowingexamplewillcleartheconcept

Example
letmutablex=10
lety=20
letmutablez=x+y
printfn"OriginalValues:"
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z

printfn"Letuschangethevalueofx"
printfn"Valueofzwillchangetoo."
x<15
z<x+y
printfn"NewValues:"
printfn"x:%i"x
printfn"y:%i"y
printfn"z:%i"z

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
OriginalValues:
x:10
y:20
z:30
Letuschangethevalueofx
Valueofzwillchangetoo.
NewValues:
x:15
y:20
z:35

UsesofMutableData
Mutabledataisoftenrequiredandusedindataprocessing,particularlywithrecorddatastructure.The
followingexampledemonstratesthis
openSystem
typestudentData=
{ID:int;
mutableIsRegistered:bool;
mutableRegisteredText:string;}
letgetStudentid=
{ID=id;
IsRegistered=false;
RegisteredText=null;}
letregisterStudents(students:studentDatalist)=
students|>List.iter(funst>
st.IsRegistered<true
st.RegisteredText<sprintf"Registered%s"(DateTime.Now.ToString("hh:mm:ss"))
Threading.Thread.Sleep(1000)(*Puttingthreadtosleepfor1secondtosimulate
processingoverhead.*))
letprintData(students:studentDatalist)=
students|>List.iter(funx>printfn"%A"x)
letmain()=
letstudents=List.init3getStudent

printfn"BeforeProcess:"
printDatastudents
printfn"Afterprocess:"
registerStudentsstudents
printDatastudents
Console.ReadKey(true)|>ignore
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
BeforeProcess:
{ID=0;
IsRegistered=false;
RegisteredText=null;}
{ID=1;
IsRegistered=false;
RegisteredText=null;}
{ID=2;
IsRegistered=false;
RegisteredText=null;}
Afterprocess:
{ID=0;
IsRegistered=true;
RegisteredText="Registered05:39:15";}
{ID=1;
IsRegistered=true;
RegisteredText="Registered05:39:16";}
{ID=2;
IsRegistered=true;
RegisteredText="Registered05:39:17";}

F#ARRAYS
Arraysarefixedsize,zerobased,mutablecollectionsofconsecutivedataelementsthatareallofthe
sametype.

CreatingArrays
YoucancreatearraysusingvarioussyntaxesandwaysorbyusingthefunctionsfromtheArraymodule.
Inthissection,wewilldiscusscreatingarrayswithoutusingthemodulefunctions.
Therearethreesyntacticalwaysofcreatingarrayswithoutfunctions
Bylistingconsecutivevaluesbetween[|and|]andseparatedbysemicolons.
Byputtingeachelementonaseparateline,inwhichcasethesemicolonseparatorisoptional.
Byusingsequenceexpressions.
Youcanaccessarrayelementsbyusingadotoperator. andbrackets[and].
Thefollowingexampledemonstratescreatingarrays
//usingsemicolonseparator

letarray1=[|1;2;3;4;5;6|]
foriin0..array1.Length1do
printf"%d"array1.[i]
printfn""
//withoutsemicolonseparator
letarray2=
[|
1
2
3
4
5
|]
foriin0..array2.Length1do
printf"%d"array2.[i]
printfn""
//usingsequence
letarray3=[|foriin1..10>i*i|]
foriin0..array3.Length1do
printf"%d"array3.[i]
printfn""

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
123456
12345
149162536496481100

BasicOperationsonArrays
ThelibrarymoduleMicrosoft.FSharp.Collections.Arraysupportsoperationsononedimensionalarrays.
ThefollowingtableshowsthebasicoperationsonArrays

Value

Description

append:'T[]'T[]'T[]

Createsanarraythatcontainstheelementsofone
arrayfollowedbytheelementsofanotherarray.

average:^T[]^T

Returnstheaverageoftheelementsinanarray.

averageBy: T U'T[]^U

Returnstheaverageoftheelementsgeneratedby
applyingafunctiontoeachelementofanarray.

blit:'T[]int'T[]intintunit

Readsarangeofelementsfromonearrayand
writesthemintoanother.

choose: T Uoption'T[]'U[]

Appliesasuppliedfunctiontoeachelementofan
array.Returnsanarraythatcontainstheresultsx
foreachelementforwhichthefunctionreturns

Somex.
collect: T U[]T[]'U[]

Appliesthesuppliedfunctiontoeachelementofan
array,concatenatestheresults,andreturnsthe
combinedarray.

concat:seq<'T[]>'T[]

Createsanarraythatcontainstheelementsofeach
ofthesuppliedsequenceofarrays.

copy:'T'T[]

Createsanarraythatcontainstheelementsofthe
suppliedarray.

create:int'T'T[]

Createsanarraywhoseelementsareallinitiallythe
suppliedvalue.

empty:'T[]

Returnsanemptyarrayofthegiventype.

exists: T bool'T[]bool

Testswhetheranyelementofanarraysatisfiesthe
suppliedpredicate.

exists2: T1 T2 bool'T1[]'T2[]
bool

Testswhetheranypairofcorrespondingelements
oftwoarrayssatisfythesuppliedcondition.

fill:'T[]intint'Tunit

Fillsarangeofelementsofanarraywiththe
suppliedvalue.

filter: T bool'T[]'T[]

Returnsacollectionthatcontainsonlythe
elementsofthesuppliedarrayforwhichthe
suppliedconditionreturnstrue.

find: T bool'T[]'T

Returnsthefirstelementforwhichthesupplied
functionreturnstrue.Raises
KeyNotFoundExceptionifnosuchelementexists.

findIndex: T bool'T[]int

Returnstheindexofthefirstelementinanarray
thatsatisfiesthesuppliedcondition.Raises
KeyNotFoundExceptionifnoneoftheelements
satisfythecondition.

fold: State T State'State'T[]


'State

Appliesafunctiontoeachelementofanarray,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthearray
elementsarei0...iN,thisfunctioncomputesf
. . . (fsi0...)iN.

fold2: State T1 T2 State'State

Appliesafunctiontopairsofelementsfromtwo

'T1[]'T2[]'State

suppliedarrays,lefttoright,threadingan
accumulatorargumentthroughthecomputation.
Thetwoinputarraysmusthavethesamelengths
otherwise,ArgumentExceptionisraised.

foldBack: T State State'T[]'State


'State

Appliesafunctiontoeachelementofanarray,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthearray
elementsarei0...iN,thisfunctioncomputesfi0
. . . (fiNs).

foldBack2: T1 T2 State State'T1[]


'T2[]'State'State

Appliesafunctiontopairsofelementsfromtwo
suppliedarrays,righttoleft,threadingan
accumulatorargumentthroughthecomputation.
Thetwoinputarraysmusthavethesamelengths
otherwise,ArgumentExceptionisraised.

forall: T bool'T[]bool

Testswhetherallelementsofanarraysatisfythe
suppliedcondition.

forall2: T1 T2 bool'T1[]'T2[]
bool

Testswhetherallcorrespondingelementsoftwo
suppliedarrayssatisfyasuppliedcondition.

get:'T[]int'T

Getsanelementfromanarray.

init:intint T'T[]

Usesasuppliedfunctiontocreateanarrayofthe
supplieddimension.

isEmpty:'T[]bool

Testswhetheranarrayhasanyelements.

iter: T unit'T[]unit

Appliesthesuppliedfunctiontoeachelementofan
array.

iter2: T1 T2 unit'T1[]'T2[]
unit)

Appliesthesuppliedfunctiontoapairofelements
frommatchingindexesintwoarrays.Thetwo
arraysmusthavethesamelengthsotherwise,
ArgumentExceptionisraised.

iteri:int T unit'T[]unit

Appliesthesuppliedfunctiontoeachelementofan
array.Theintegerpassedtothefunctionindicates
theindexoftheelement.

iteri2:int T1 T2 unit'T1[]'T2[]
unit

Appliesthesuppliedfunctiontoapairofelements
frommatchingindexesintwoarrays,alsopassing
theindexoftheelements.Thetwoarraysmust
havethesamelengthsotherwise,an

ArgumentExceptionisraised.
length:'T[]int

Returnsthelengthofanarray.TheLength
propertydoesthesamething.

map: T U'T[]'U[]

Createsanarraywhoseelementsaretheresultsof
applyingthesuppliedfunctiontoeachofthe
elementsofasuppliedarray.

map2: T1 T2 U'T1[]'T2[]'U
[]

Createsanarraywhoseelementsaretheresultsof
applyingthesuppliedfunctiontothe
correspondingelementsoftwosuppliedarrays.
Thetwoinputarraysmusthavethesamelengths
otherwise,ArgumentExceptionisraised.

mapi:int T U'T[]'U[]

Createsanarraywhoseelementsaretheresultsof
applyingthesuppliedfunctiontoeachofthe
elementsofasuppliedarray.Anintegerindex
passedtothefunctionindicatestheindexofthe
elementbeingtransformed.

mapi2:int T1 T2 U'T1[]'T2[]
'U[]

Createsanarraywhoseelementsaretheresultsof
applyingthesuppliedfunctiontothe
correspondingelementsofthetwocollections
pairwise,alsopassingtheindexoftheelements.
Thetwoinputarraysmusthavethesamelengths
otherwise,ArgumentExceptionisraised.

max:'T[]'T

Returnsthelargestofallelementsofanarray.
Operators.maxisusedtocomparetheelements.

maxBy: T U'T[]'T

Returnsthelargestofallelementsofanarray,
comparedviaOperators.maxonthefunction
result.

min:('T[]'T

Returnsthesmallestofallelementsofanarray.
Operators.minisusedtocomparetheelements.

minBy: T U'T[]'T

Returnsthesmallestofallelementsofanarray.
Operators.minisusedtocomparetheelements.

ofList:'Tlist'T[]

Createsanarrayfromthesuppliedlist.

ofSeq:seq<'T>'T[]

Createsanarrayfromthesuppliedenumerable
object.

partition: T bool'T[]'T[]*'T[]

Splitsanarrayintotwoarrays,onecontainingthe
elementsforwhichthesuppliedconditionreturns
true,andtheothercontainingthoseforwhichit
returnsfalse.

permute:int int'T[]'T[]

Permutestheelementsofanarrayaccordingtothe
specifiedpermutation.

pick: T Uoption'T[]'U

Appliesthesuppliedfunctiontosuccessive
elementsofasuppliedarray,returningthefirst
resultwherethefunctionreturnsSomexforsome
x.IfthefunctionneverreturnsSomex,
KeyNotFoundExceptionisraised.

reduce: T T T'T[]'T

Appliesafunctiontoeachelementofanarray,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthearray
elementsarei0...iN,thisfunctioncomputesf
. . . (fi0i1...)iN.Ifthearrayhassizezero,
ArgumentExceptionisraised.

reduceBack: T T T'T[]'T

Appliesafunctiontoeachelementofanarray,
threadinganaccumulatorargumentthroughthe
computation.Iftheinputfunctionisfandthe
elementsarei0...iN,thisfunctioncomputesfi0
. . . (fiN 1iN).Ifthearrayhassizezero,
ArgumentExceptionisraised.

rev:'T[]'T[]

Reversestheorderoftheelementsinasupplied
array.

scan: State T State'State'T[]


'State[])

Behaveslikefold,butreturnstheintermediate
resultstogetherwiththefinalresults.

scanBack: T State State'T[]'State


'State[]

BehaveslikefoldBack,butreturnstheintermediary
resultstogetherwiththefinalresults.

set:'T[]int'Tunit

Setsanelementofanarray.

sort:'T[]'T[]

Sortstheelementsofanarrayandreturnsanew
array.Operators.compareisusedtocomparethe
elements.

sortBy: T Key'T[]'T[]

Sortstheelementsofanarraybyusingthe
suppliedfunctiontotransformtheelementstothe
typeonwhichthesortoperationisbased,and

returnsanewarray.Operators.compareisusedto
comparetheelements.
sortInPlace:'T[]unit

Sortstheelementsofanarraybychangingthe
arrayinplace,usingthesuppliedcomparison
function.Operators.compareisusedtocompare
theelements.

sortInPlaceBy: T Key'T[]unit

Sortstheelementsofanarraybychangingthe
arrayinplace,usingthesuppliedprojectionforthe
keys.Operators.compareisusedtocomparethe
elements.

sortInPlaceWith: T T int'T[]unit

Sortstheelementsofanarraybyusingthe
suppliedcomparisonfunctiontochangethearray
inplace.

sortWith: T T int'T[]'T[]

Sortstheelementsofanarraybyusingthe
suppliedcomparisonfunction,andreturnsanew
array.

sub:'T[]intint'T[]

Createsanarraythatcontainsthesupplied
subrange,whichisspecifiedbystartingindexand
length.

sum:'T[]^T

Returnsthesumoftheelementsinthearray.

sumBy: T U'T[]^U

Returnsthesumoftheresultsgeneratedby
applyingafunctiontoeachelementofanarray.

toList:'T[]'Tlist

Convertsthesuppliedarraytoalist.

toSeq:'T[]seq<'T>

Viewsthesuppliedarrayasasequence.

tryFind: T bool'T[]'Toption

Returnsthefirstelementinthesuppliedarrayfor
whichthesuppliedfunctionreturnstrue.Returns
Noneifnosuchelementexists.

tryFindIndex: T bool'T[]intoption

Returnstheindexofthefirstelementinanarray
thatsatisfiesthesuppliedcondition.

tryPick: T Uoption'T[]'Uoption

Appliesthesuppliedfunctiontosuccessive
elementsofthesuppliedarray,andreturnsthe
firstresultwherethefunctionreturnsSomexfor
somex.IfthefunctionneverreturnsSomex,None
isreturned.

unzip: T1 T2[]'T1[]*'T2[]

Splitsanarrayoftuplepairsintoatupleoftwo
arrays.

unzip3: T1 T2 T3[]'T1[]*'T2[]*'T3
[]

Splitsanarrayoftuplesofthreeelementsintoa
tupleofthreearrays.

zeroCreate:int'T[]

Createsanarraywhoseelementsareinitiallysetto
thedefaultvalueUnchecked.defaultof<'T>.

zip:'T1[]'T2[] T1 T2[]

Combinestwoarraysintoanarrayoftuplesthat
havetwoelements.Thetwoarraysmusthaveequal
lengthsotherwise,ArgumentExceptionisraised.

zip3:'T1[]'T2[]'T3[]
T1 T2 113 T3[]

Combinesthreearraysintoanarrayoftuplesthat
havethreeelements.Thethreearraysmusthave
equallengthsotherwise,ArgumentExceptionis
raised.

Inthefollowingsection,wewillseetheusesofsomeofthesefunctionalities.

CreatingArraysUsingFunctions
TheArraymoduleprovidesseveralfunctionsthatcreateanarrayfromscratch.
TheArray.emptyfunctioncreatesanewemptyarray.
TheArray.createfunctioncreatesanarrayofaspecifiedsizeandsetsalltheelementstogiven
values.
TheArray.initfunctioncreatesanarray,givenadimensionandafunctiontogeneratethe
elements.
TheArray.zeroCreatefunctioncreatesanarrayinwhichalltheelementsareinitializedtothe
zerovalue.
TheArray.copyfunctioncreatesanewarraythatcontainselementsthatarecopiedfroman
existingarray.
TheArray.subfunctiongeneratesanewarrayfromasubrangeofanarray.
TheArray.appendfunctioncreatesanewarraybycombiningtwoexistingarrays.
TheArray.choosefunctionselectselementsofanarraytoincludeinanewarray.
TheArray.collectfunctionrunsaspecifiedfunctiononeacharrayelementofanexistingarray
andthencollectstheelementsgeneratedbythefunctionandcombinesthemintoanewarray.
TheArray.concatfunctiontakesasequenceofarraysandcombinesthemintoasinglearray.
TheArray.filterfunctiontakesaBooleanconditionfunctionandgeneratesanewarraythat
containsonlythoseelementsfromtheinputarrayforwhichtheconditionistrue.

TheArray.revfunctiongeneratesanewarraybyreversingtheorderofanexistingarray.
Thefollowingexamplesdemonstratethesefunctions

Example1
(*usingcreateandset*)
letarray1=Array.create10""
foriin0..array1.Length1do
Array.setarray1i(i.ToString())
foriin0..array1.Length1do
printf"%s"(Array.getarray1i)
printfn""
(*emptyarray*)
letarray2=Array.empty
printfn"Lengthofemptyarray:%d"array2.Length
letarray3=Array.create107.0
printfn"FloatArray:%A"array3
(*usingtheinitandzeroCreate*)
letarray4=Array.init10(funindex>index*index)
printfn"Arrayofsquares:%A"array4
letarray5:floatarray=Array.zeroCreate10
let(myZeroArray:floatarray)=Array.zeroCreate10
printfn"FloatArray:%A"array5

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
0123456789
Lengthofemptyarray:0
FloatArray:[|7.0;7.0;7.0;7.0;7.0;7.0;7.0;7.0;7.0;7.0|]
Arrayofsquares:[|0;1;4;9;16;25;36;49;64;81|]
FloatArray:[|0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0;0.0|]

Example2
(*creatingsubarrayfromelement5*)
(*containing15elementsthereon*)
letarray1=[|0..50|]
letarray2=Array.subarray1515
printfn"SubArray:"
printfn"%A"array2
(*appendingtwoarrays*)
letarray3=[|1;2;3;4|]
letarray4=[|5..9|]
printfn"AppendedArray:"
letarray5=Array.appendarray3array4
printfn"%A"array5
(*usingtheChoosefunction*)

letarray6=[|1..20|]
letarray7=Array.choose(funelem>ifelem%3=0then
Some(float(elem))
else
None)array6
printfn"ArraywithChosenelements:"
printfn"%A"array7
(*usingtheCollectfunction*)
letarray8=[|2..5|]
letarray9=Array.collect(funelem>[|0..elem1|])array8
printfn"Arraywithcollectedelements:"
printfn"%A"array9

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
SubArray:
[|5;6;7;8;9;10;11;12;13;14;15;16;17;18;19|]
AppendedArray:
[|1;2;3;4;5;6;7;8;9|]
ArraywithChosenelements:
[|3.0;6.0;9.0;12.0;15.0;18.0|]
Arraywithcollectedelements:
[|0;1;0;1;2;0;1;2;3;0;1;2;3;4|]

SearchingArrays
TheArray.findfunctiontakesaBooleanfunctionandreturnsthefirstelementforwhichthefunction
returnstrue,elseraisesaKeyNotFoundException.
TheArray.findIndexfunctionworkssimilarlyexceptthatitreturnstheindexoftheelementinsteadof
theelementitself.
Thefollowingexampledemonstratesthis.
Microsoftprovidesthisinterestingprogramexample,whichfindsthefirstelementintherangeofa
givennumberthatisbothaperfectsquareaswellasaperfectcube
letarray1=[|2..100|]
letdelta=1.0e10
letisPerfectSquare(x:int)=
lety=sqrt(floatx)
abs(yroundy)<delta
letisPerfectCube(x:int)=
lety=System.Math.Pow(floatx,1.0/3.0)
abs(yroundy)<delta
letelement=Array.find(funelem>isPerfectSquareelem&&isPerfectCubeelem)array1
letindex=Array.findIndex(funelem>isPerfectSquareelem&&isPerfectCubeelem)
array1
printfn"Thefirstelementthatisbothasquareandacubeis%danditsindexis%d."
elementindex

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Thefirstelementthatisbothasquareandacubeis64anditsindexis62.

F#MUTABLELISTS
TheList<'T>classrepresentsastronglytypedlistofobjectsthatcanbeaccessedbyindex.
ItisamutablecounterpartoftheListclass.Itissimilartoarrays,asitcanbeaccessedbyanindex,
however,unlikearrays,listscanberesized.Thereforeyouneednotspecifyasizeduringdeclaration.

CreatingaMutableList
Listsarecreatedusingthenewkeywordandcallingthelist'sconstructor.Thefollowingexample
demonstratesthis
(*CreatingaList*)
openSystem.Collections.Generic
letbooksList=newList<string>()
booksList.Add("GonewiththeWind")
booksList.Add("AtlasShrugged")
booksList.Add("Fountainhead")
booksList.Add("Thornbirds")
booksList.Add("Rebecca")
booksList.Add("Narnia")
booksList|>Seq.iteri(funindexitem>printfn"%i:%s"indexbooksList.[index])

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
0:GonewiththeWind
1:AtlasShrugged
2:Fountainhead
3:Thornbirds
4:Rebecca
5:Narnia

TheListTClass
TheListTclassrepresentsastronglytypedlistofobjectsthatcanbeaccessedbyindex.Itprovide
methodstosearch,sort,andmanipulatelists.
Thefollowingtablesprovidetheproperties,constructorsandthemethodsoftheListTclass

Properties
Property

Description

Capacity

Getsorsetsthetotalnumberofelementstheinternaldatastructurecanholdwithout
resizing.

Count

GetsthenumberofelementscontainedintheListT.

Item

Getsorsetstheelementatthespecifiedindex.

Constructors
Constructor

Description

ListT

InitializesanewinstanceoftheListTclassthatisemptyandhasthe
defaultinitialcapacity.

ListTIEnumerable(T)

InitializesanewinstanceoftheListTclassthatcontainselements
copiedfromthespecifiedcollectionandhassufficientcapacityto
accommodatethenumberofelementscopied.

ListTInt32

InitializesanewinstanceoftheListTclassthatisemptyandhasthe
specifiedinitialcapacity.

Method
Methods

Description

Add

AddsanobjecttotheendoftheListT.

AddRange

Addstheelementsofthespecifiedcollectiontothe
endoftheListT.

AsReadOnly

ReturnsareadonlyIListTwrapperforthecurrent
collection.

BinarySearchT

SearchestheentiresortedListTforanelementusing
thedefaultcomparerandreturnsthezerobasedindex
oftheelement.

BinarySearchT, IComparer(T)

SearchestheentiresortedListTforanelementusing
thespecifiedcomparerandreturnsthezerobased
indexoftheelement.

BinarySearchInt32, Int32, T, IComparer(T)

SearchesarangeofelementsinthesortedListTforan
elementusingthespecifiedcomparerandreturnsthe
zerobasedindexoftheelement.

Clear

RemovesallelementsfromtheListT.

Contains

DetermineswhetheranelementisintheListT.

ConvertAllTOutput

ConvertstheelementsinthecurrentListTtoanother
type,andreturnsalistcontainingtheconverted
elements.

CopyToT[]

CopiestheentireListTtoacompatibleone
dimensionalarray,startingatthebeginningofthe
targetarray.

CopyToT[], Int32

CopiestheentireListTtoacompatibleone
dimensionalarray,startingatthespecifiedindexof
thetargetarray.

CopyToInt32, T[], Int32, Int32

CopiesarangeofelementsfromtheListTtoa
compatibleonedimensionalarray,startingatthe
specifiedindexofthetargetarray.

EqualsObject

Determineswhetherthespecifiedobjectisequalto
thecurrentobject.InheritedfromObject.

Exists

DetermineswhethertheListTcontainselementsthat
matchtheconditionsdefinedbythespecified
predicate.

Finalize

Allowsanobjecttotrytofreeresourcesandperform
othercleanupoperationsbeforeitisreclaimedby
garbagecollectionInheritedfromObject.

Find

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
firstoccurrencewithintheentireListT.

FindAll

Retrievesalltheelementsthatmatchtheconditions
definedbythespecifiedpredicate.

FindIndexPredicate(T)

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
zerobasedindexofthefirstoccurrencewithinthe
entireListT.

FindIndexInt32, Predicate(T)

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
zerobasedindexofthefirstoccurrencewithinthe
rangeofelementsintheListTthatextendsfromthe
specifiedindextothelastelement.

FindIndexInt32, Int32, Predicate(T)

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
zerobasedindexofthefirstoccurrencewithinthe
rangeofelementsintheListTthatstartsatthe
specifiedindexandcontainsthespecifiednumberof
elements.

FindLast

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthelast
occurrencewithintheentireListT.

FindLastIndexPredicate(T)

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
zerobasedindexofthelastoccurrencewithinthe
entireListT.

FindLastIndexInt32, Predicate(T)

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
zerobasedindexofthelastoccurrencewithinthe
rangeofelementsintheListTthatextendsfromthe
firstelementtothespecifiedindex.

FindLastIndexInt32, Int32, Predicate(T)

Searchesforanelementthatmatchestheconditions
definedbythespecifiedpredicate,andreturnsthe
zerobasedindexofthelastoccurrencewithinthe
rangeofelementsintheListTthatcontainsthe
specifiednumberofelementsandendsatthespecified
index.

ForEach

Performsthespecifiedactiononeachelementofthe
ListT.

GetEnumerator

ReturnsanenumeratorthatiteratesthroughtheListT
.

GetHashCode

Servesasthedefaulthashfunction.
InheritedfromObject.

GetRange

Createsashallowcopyofarangeofelementsinthe
sourceListT.

GetType

GetstheTypeofthecurrentinstance.
InheritedfromObject.

IndexOfT

Searchesforthespecifiedobjectandreturnsthezero

basedindexofthefirstoccurrencewithintheentire
ListT.
IndexOfT, Int32

Searchesforthespecifiedobjectandreturnsthezero
basedindexofthefirstoccurrencewithintherangeof
elementsintheListTthatextendsfromthespecified
indextothelastelement.

IndexOfT, Int32, Int32

Searchesforthespecifiedobjectandreturnsthezero
basedindexofthefirstoccurrencewithintherangeof
elementsintheListTthatstartsatthespecifiedindex
andcontainsthespecifiednumberofelements.

Insert

InsertsanelementintotheListTatthespecifiedindex.

InsertRange

InsertstheelementsofacollectionintotheListTat
thespecifiedindex.

LastIndexOfT

Searchesforthespecifiedobjectandreturnsthezero
basedindexofthelastoccurrencewithintheentire
ListT.

LastIndexOfT, Int32

Searchesforthespecifiedobjectandreturnsthezero
basedindexofthelastoccurrencewithintherangeof
elementsintheListTthatextendsfromthefirst
elementtothespecifiedindex.

LastIndexOfT, Int32, Int32

Searchesforthespecifiedobjectandreturnsthezero
basedindexofthelastoccurrencewithintherangeof
elementsintheListTthatcontainsthespecified
numberofelementsandendsatthespecifiedindex.

MemberwiseClone

CreatesashallowcopyofthecurrentObject.
InheritedfromObject.

Remove

Removesthefirstoccurrenceofaspecificobjectfrom
theListT.

RemoveAll

Removesalltheelementsthatmatchtheconditions
definedbythespecifiedpredicate.

RemoveAt

RemovestheelementatthespecifiedindexoftheList
T.

RemoveRange

RemovesarangeofelementsfromtheListT.

Reverse

ReversestheorderoftheelementsintheentireListT.

ReverseInt32, Int32

Reversestheorderoftheelementsinthespecified
range.

Sort

SortstheelementsintheentireListTusingthedefault
comparer.

SortComparison(T)

SortstheelementsintheentireListTusingthe
specifiedSystem.ComparisonT.

SortIComparer(T)

SortstheelementsintheentireListTusingthe
specifiedcomparer.

SortInt32, Int32, IComparer(T)

SortstheelementsinarangeofelementsinListT
usingthespecifiedcomparer.

ToArray

CopiestheelementsoftheListTtoanewarray.

ToString

Returnsastringthatrepresentsthecurrentobject.
InheritedfromObject.

TrimExcess

Setsthecapacitytotheactualnumberofelementsin
theListT,ifthatnumberislessthanathresholdvalue.

TrueForAll

DetermineswhethereveryelementintheListT
matchestheconditionsdefinedbythespecified
predicate.

Example
(*CreatingaList*)
openSystem.Collections.Generic
letbooksList=newList<string>()
booksList.Add("GonewiththeWind")
booksList.Add("AtlasShrugged")
booksList.Add("Fountainhead")
booksList.Add("Thornbirds")
booksList.Add("Rebecca")
booksList.Add("Narnia")
printfn"Total%dbooks"booksList.Count
booksList|>Seq.iteri(funindexitem>printfn"%i:%s"indexbooksList.[index])
booksList.Insert(2,"Roots")
printfn("afterinsertingatindex2")
printfn"Total%dbooks"booksList.Count
booksList|>Seq.iteri(funindexitem>printfn"%i:%s"indexbooksList.[index])

booksList.RemoveAt(3)
printfn("afterremovingfromindex3")
printfn"Total%dbooks"booksList.Count
booksList|>Seq.iteri(funindexitem>printfn"%i:%s"indexbooksList.[index])

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Total6books
0:GonewiththeWind
1:AtlasShrugged
2:Fountainhead
3:Thornbirds
4:Rebecca
5:Narnia
afterinsertingatindex2
Total7books
0:GonewiththeWind
1:AtlasShrugged
2:Roots
3:Fountainhead
4:Thornbirds
5:Rebecca
6:Narnia
afterremovingfromindex3
Total6books
0:GonewiththeWind
1:AtlasShrugged
2:Roots
3:Thornbirds
4:Rebecca
5:Narnia

F#MUTABLEDICTIONARY
TheDictionary<'TKey,'TValue>classisthemutableanalogoftheF#mapdatastructureand
containsmanyofthesamefunctions.
RecapitulatingfromtheMapchapterinF#,amapisaspecialkindofsetthatassociatesthevalueswith
key.

CreatingofaMutableDictionary
Mutabledictionariesarecreatedusingthenewkeywordandcallingthelist'sconstructor.Thefollowing
exampledemonstratesthis
openSystem.Collections.Generic
letdict=newDictionary<string,string>()
dict.Add("1501","ZaraAli")
dict.Add("1502","RishitaGupta")
dict.Add("1503","RobinSahoo")
dict.Add("1504","GillianMegan")
printfn"Dictionarystudents:%A"dict

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput

Dictionarystudents:seq
[[1501,ZaraAli];[1502,RishitaGupta];[1503,RobinSahoo];
[1504,GillianMegan]]

TheDictionaryTKey, TValueClass
TheDictionaryTKey, TValueClassrepresentsacollectionofkeysandvalues.
Thefollowingtablesprovidetheproperties,constructorsandthemethodsoftheListTclass

Properties
Property

Description

Comparer

GetstheIEqualityComparerTthatisusedtodetermineequalityofkeysforthe
dictionary.

Count

Getsthenumberofkey/valuepairscontainedintheDictionaryTKey, TValue.

Item

Getsorsetsthevalueassociatedwiththespecifiedkey.

Keys

GetsacollectioncontainingthekeysintheDictionaryTKey, TValue.

Values

GetsacollectioncontainingthevaluesintheDictionaryTKey, TValue.

Constructors
Constructors

Description

DictionaryTKey, TValue

InitializesanewinstanceoftheDictionaryTKey, TValueclass
thatisempty,hasthedefaultinitialcapacity,andusesthedefault
equalitycomparerforthekeytype.

DictionaryTKey, TValue
IDictionary(TKey, TValue)

InitializesanewinstanceoftheDictionaryTKey, TValueclass
thatcontainselementscopiedfromthespecifiedIDictionary
TKey, TValueandusesthedefaultequalitycomparerforthekey
type.

DictionaryTKey, TValue
IEqualityComparer(TKey)

InitializesanewinstanceoftheDictionaryTKey, TValueclass
thatisempty,hasthedefaultinitialcapacity,andusesthe
specifiedIEqualityComparerT.

DictionaryTKey, TValueInt32

InitializesanewinstanceoftheDictionaryTKey, TValueclass
thatisempty,hasthespecifiedinitialcapacity,andusesthe
defaultequalitycomparerforthekeytype.

DictionaryTKey, TValue
IDictionary(TKey, TValue,
IEqualityComparerTKey)

InitializesanewinstanceoftheDictionaryTKey, TValueclass
thatcontainselementscopiedfromthespecifiedIDictionary
TKey, TValueandusesthespecifiedIEqualityComparerT.

DictionaryTKey, TValue
Int32, IEqualityComparer(TKey)

InitializesanewinstanceoftheDictionaryTKey, TValueclass
thatisempty,hasthespecifiedinitialcapacity,andusesthe
specifiedIEqualityComparerT.

DictionaryTKey, TValue
SerializationInfo, StreamingContext

InitializesanewinstanceoftheictionaryTKey, TValueclasswith
serializeddata.

Methods
Method

Description

Add

Addsthespecifiedkeyandvaluetothedictionary.

Clear

RemovesallkeysandvaluesfromtheDictionaryTKey, TValue.

ContainsKey

DetermineswhethertheDictionaryTKey, TValuecontainsthespecifiedkey.

ContainsValue

DetermineswhethertheDictionaryTKey, TValuecontainsaspecificvalue.

EqualsObject

Determineswhetherthespecifiedobjectisequaltothecurrentobject.
InheritedfromObject.

Finalize

Allowsanobjecttotrytofreeresourcesandperformothercleanupoperations
beforeitisreclaimedbygarbagecollection.InheritedfromObject.

GetEnumerator

ReturnsanenumeratorthatiteratesthroughtheDictionaryTKey, TValue.

GetHashCode

Servesasthedefaulthashfunction.InheritedfromObject.

GetObjectData

ImplementstheSystem.Runtime.Serialization.ISerializableinterfaceand
returnsthedataneededtoserializetheDictionaryTKey, TValueinstance.

GetType

GetstheTypeofthecurrentinstance.InheritedfromObject.

MemberwiseClone

CreatesashallowcopyofthecurrentObject.InheritedfromObject.

OnDeserialization

ImplementstheSystem.Runtime.Serialization.ISerializableinterfaceandraises
thedeserializationeventwhenthedeserializationiscomplete.

Remove

RemovesthevaluewiththespecifiedkeyfromtheDictionaryTKey, TValue.

ToString

Returnsastringthatrepresentsthecurrentobject.InheritedfromObject.

TryGetValue

Getsthevalueassociatedwiththespecifiedkey.

Example
openSystem.Collections.Generic
letdict=newDictionary<string,string>()
dict.Add("1501","ZaraAli")
dict.Add("1502","RishitaGupta")
dict.Add("1503","RobinSahoo")
dict.Add("1504","GillianMegan")
printfn"Dictionarystudents:%A"dict
printfn"TotalNumberofStudents:%d"dict.Count
printfn"Thekeys:%A"dict.Keys
printf"TheValues:%A"dict.Values

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Dictionarystudents:seq
[[1501,ZaraAli];[1502,RishitaGupta];[1503,RobinSahoo];
[1504,GillianMegan]]
TotalNumberofStudents:4
Thekeys:seq["1501";"1502";"1503";"1504"]
TheValues:seq["ZaraAli";"RishitaGupta";"RobinSahoo";"GillianMegan"]

F#BASICIO
BasicInputOutputincludes
Readingfromandwritingintoconsole.
Readingfromandwritingintofile.

Core.PrintfModule
Wehaveusedtheprintfandtheprintfnfunctionsforwritingintotheconsole.Inthissection,wewill
lookintothedetailsofthePrintfmoduleofF#.
Apartfromtheabovefunctions,theCore.PrintfmoduleofF#hasvariousothermethodsforprinting
andformattingusing%markersasplaceholders.Thefollowingtableshowsthemethodswithbrief
description

Value

Description

bprintf:StringBuilderBuilderFormat<'T>
'T

PrintstoaStringBuilder.

eprintf:TextWriterFormat<'T>'T

Printsformattedoutputtostderr.

eprintfn:TextWriterFormat<'T>'T

Printsformattedoutputtostderr,addinga
newline.

failwithf:StringFormat<'T,'Result>'T

Printstoastringbufferandraisesanexception
withthegivenresult.

fprintf:TextWriterTextWriterFormat<'T>
'T

Printstoatextwriter.

fprintfn:TextWriterTextWriterFormat<'T>
'T

Printstoatextwriter,addinganewline.

kbprintf:unit ResultStringBuilder
BuilderFormat<'T,'Result>'T

Likebprintf,butcallsthespecifiedfunctionto
generatetheresult.

kfprintf:unit ResultTextWriter
TextWriterFormat<'T,'Result>'T

Likefprintf,butcallsthespecifiedfunctionto
generatetheresult.

kprintf:string Result
StringFormat<'T,'Result>'T

Likeprintf,butcallsthespecifiedfunctionto
generatetheresult.Forexample,theseletthe
printingforceaflushafteralloutputhasbeen
enteredontothechannel,butnotbefore.

ksprintf:string Result
StringFormat<'T,'Result>'T

Likesprintf,butcallsthespecifiedfunctionto
generatetheresult.

printf:TextWriterFormat<'T>'T

Printsformattedoutputtostdout.

printfn:TextWriterFormat<'T>'T

Printsformattedoutputtostdout,addinga
newline.

sprintf:StringFormat<'T>'T

Printstoastringbyusinganinternalstring
bufferandreturnstheresultasastring.

FormatSpecifications
Formatspecificationsareusedforformattingtheinputoroutput,accordingtotheprogrammersneed.
Thesearestringswith%markersindicatingformatplaceholders.
ThesyntaxofaFormatplaceholdersis
%[flags][width][.precision][type]

Thetypeisinterpretedas

Type

Description

%b

Formatsabool,formattedastrueorfalse.

%c

Formatsacharacter.

%s

Formatsastring,formattedasitscontents,withoutinterpretingany
escapecharacters.

%d,%i

Formatsanybasicintegertypeformattedasadecimalinteger,signedif
thebasicintegertypeissigned.

%u

Formatsanybasicintegertypeformattedasanunsigneddecimal
integer.

%x

Formatsanybasicintegertypeformattedasanunsignedhexadecimal
integer,usinglowercaselettersathroughf.

%X

Formatsanybasicintegertypeformattedasanunsignedhexadecimal
integer,usinguppercaselettersAthroughF.

%o

Formatsanybasicintegertypeformattedasanunsignedoctalinteger.

%e,%E,%f,%F,%g,%G

Formatsanybasicfloatingpointtypefloat, float32formattedusingaC
stylefloatingpointformatspecifications.

%e,%E

Formatsasignedvaluehavingtheform[]d.dddde[sign]dddwheredisa
singledecimaldigit,ddddisoneormoredecimaldigits,dddisexactly
threedecimaldigits,andsignis+or.

%f

Formatsasignedvaluehavingtheform[]dddd.dddd,whereddddis
oneormoredecimaldigits.Thenumberofdigitsbeforethedecimal
pointdependsonthemagnitudeofthenumber,andthenumberof
digitsafterthedecimalpointdependsontherequestedprecision.

%g,%G

Formatsasignedvalueprintedinforeformat,whicheverismore
compactforthegivenvalueandprecision.

%M

FormatsaDecimalvalue.

%O

Formatsanyvalue,printedbyboxingtheobjectandusingitsToString
method.

%A,%+A

Formatsanyvalue,printedwiththedefaultlayoutsettings.Use%+Ato
printthestructureofdiscriminatedunionswithinternalandprivate
representations.

%a

Ageneralformatspecifier,requirestwoarguments.Thefirstargument
isafunctionwhichacceptstwoarguments:first,acontextparameterof
theappropriatetypeforthegivenformattingfunction
forexample, aTextWriter,andsecond,avaluetoprintandwhicheither
outputsorreturnsappropriatetext.
Thesecondargumentistheparticularvaluetoprint.

%t

Ageneralformatspecifier,requiresoneargument:afunctionwhich
acceptsacontextparameteroftheappropriatetypeforthegiven
formattingfunctionaTextWriterandwhicheitheroutputsorreturns
appropriatetext.Basicintegertypesarebyte,sbyte,int16,uint16,
int32,uint32,int64,uint64,nativeint,andunativeint.Basic
floatingpointtypesarefloatandfloat32.

Thewidthisanoptionalparameter.Itisanintegerthatindicatestheminimalwidthoftheresult.For
example,%5dprintsanintegerwithatleastspacesof5characters.
Validflagsaredescribedinthefollowingtable

Value

Description

Specifiestoaddzerosinsteadofspacestomakeuptherequiredwidth.

Specifiestoleftjustifytheresultwithinthewidthspecified.

Specifiestoadda+characterifthenumberispositivetomatcha signfornegativenumbers.

''space

Specifiestoaddanextraspaceifthenumberispositivetomatcha signfornegativenumbers.

Invalid.

Example
printf"Hello"
printf"World"
printfn""
printfn"Hello"
printfn"World"
printf"Hi,I'm%sandI'ma%s""Rohit""MedicalStudent"
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

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
HelloWorld
Hello
World
Hi,I'mRohitandI'maMedicalStudentd:212.098000
e:504.768000
x:212.098
y:504.768
x:2.120980e+002
y:5.047680e+002
True:true

TheConsoleClass
Thisclassisapartofthe.NETframework.Itrepresentsthestandardinput,output,anderrorstreams
forconsoleapplications.
Itprovidesvariousmethodsforreadingfromandwritingintotheconsole.Thefollowingtableshowsthe
methods

Method

Description

Beep

Playsthe
soundofa
beepthrough
theconsole
speaker.

BeepInt32, Int32

Playsthe
soundofa
beepofa
specified
frequencyand
duration
throughthe
console
speaker.

Clear

Clearsthe
consolebuffer
and
corresponding
console

windowof
display
information.
MoveBufferAreaInt32, Int32, Int32, Int32, Int32, Int32

Copiesa
specified
sourceareaof
thescreen
buffertoa
specified
destination
area.

MoveBufferAreaInt32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor

Copiesa
specified
sourceareaof
thescreen
buffertoa
specified
destination
area.

OpenStandardError

Acquiresthe
standarderror
stream.

OpenStandardErrorInt32

Acquiresthe
standarderror
stream,which
issettoa
specified
buffersize.

OpenStandardInput

Acquiresthe
standardinput
stream.

OpenStandardInputInt32

Acquiresthe
standardinput
stream,which
issettoa
specified
buffersize.

OpenStandardOutput

Acquiresthe
standard
outputstream.

OpenStandardOutputInt32

Acquiresthe
standard
outputstream,
whichissetto
aspecified
buffersize.

Read

Readsthenext
characterfrom
thestandard
inputstream.

ReadKey

Obtainsthe
nextcharacter
orfunction
keypressedby
theuser.The
pressedkeyis
displayedin
theconsole
window.

ReadKeyBoolean

Obtainsthe
nextcharacter
orfunction
keypressedby
theuser.The
pressedkeyis
optionally
displayedin
theconsole
window.

ReadLine

Readsthenext
lineof
characters
fromthe
standardinput
stream.

ResetColor

Setsthe

foreground
and
background
consolecolors
totheir
defaults.
SetBufferSize

Setstheheight
andwidthof
thescreen
bufferareato
thespecified
values.

SetCursorPosition

Setsthe
positionofthe
cursor.

SetError

SetstheError
propertyto
thespecified
TextWriter
object.

SetIn

SetstheIn
propertyto
thespecified
TextReader
object.

SetOut

SetstheOut
propertyto
thespecified
TextWriter
object.

SetWindowPosition

Setsthe
positionofthe
console
window
relativetothe
screenbuffer.

SetWindowSize

Setstheheight
andwidthof

theconsole
windowtothe
specified
values.
WriteBoolean

Writesthetext
representation
ofthe
specified
Booleanvalue
tothe
standard
outputstream.

WriteChar

Writesthe
specified
Unicode
character
valuetothe
standard
outputstream.

WriteChar[]

Writesthe
specifiedarray
ofUnicode
charactersto
thestandard
outputstream.

WriteDecimal

Writesthetext
representation
ofthe
specified
Decimalvalue
tothe
standard
outputstream.

WriteDouble

Writesthetext
representation
ofthe
specified
double
precision
floatingpoint

valuetothe
standard
outputstream.
WriteInt32

Writesthetext
representation
ofthe
specified32
bitsigned
integervalue
tothe
standard
outputstream.

WriteInt64

Writesthetext
representation
ofthe
specified64
bitsigned
integervalue
tothe
standard
outputstream.

WriteObject

Writesthetext
representation
ofthe
specified
objecttothe
standard
outputstream.

WriteSingle

Writesthetext
representation
ofthe
specified
single
precision
floatingpoint
valuetothe
standard
outputstream.

WriteString

Writesthe

specified
stringvalueto
thestandard
outputstream.
WriteUInt32

Writesthetext
representation
ofthe
specified32
bitunsigned
integervalue
tothe
standard
outputstream.

WriteUInt64

Writesthetext
representation
ofthe
specified64
bitunsigned
integervalue
tothe
standard
outputstream.

WriteString, Object

Writesthetext
representation
ofthe
specified
objecttothe
standard
outputstream
usingthe
specified
format
information.

WriteString, Object[]

Writesthetext
representation
ofthe
specifiedarray
ofobjectsto
thestandard
outputstream

usingthe
specified
format
information.
WriteChar[], Int32, Int32

Writesthe
specified
subarrayof
Unicode
charactersto
thestandard
outputstream.

WriteString, Object, Object

Writesthetext
representation
ofthe
specified
objectstothe
standard
outputstream
usingthe
specified
format
information.

WriteString, Object, Object, Object

Writesthetext
representation
ofthe
specified
objectstothe
standard
outputstream
usingthe
specified
format
information.

WriteString, Object, Object, Object, Object

Writesthetext
representation
ofthe
specified
objectsand
variable
length

parameterlist
tothe
standard
outputstream
usingthe
specified
format
information.
WriteLine

Writesthe
currentline
terminatorto
thestandard
outputstream.

WriteLineBoolean

Writesthetext
representation
ofthe
specified
Booleanvalue,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineChar

Writesthe
specified
Unicode
character,
followedby
thecurrent
line
terminator,
valuetothe
standard
outputstream.

WriteLineChar[]

Writesthe
specifiedarray
ofUnicode
characters,
followedby

thecurrent
line
terminator,to
thestandard
outputstream.
WriteLineDecimal

Writesthetext
representation
ofthe
specified
Decimalvalue,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineDouble

Writesthetext
representation
ofthe
specified
double
precision
floatingpoint
value,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineInt32

Writesthetext
representation
ofthe
specified32
bitsigned
integervalue,
followedby
thecurrent
line
terminator,to
thestandard

outputstream.
WriteLineInt64

Writesthetext
representation
ofthe
specified64
bitsigned
integervalue,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineObject

Writesthetext
representation
ofthe
specified
object,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineSingle

Writesthetext
representation
ofthe
specified
single
precision
floatingpoint
value,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineString

Writesthe
specified

stringvalue,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.
WriteLineUInt32

Writesthetext
representation
ofthe
specified32
bitunsigned
integervalue,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineUInt64

Writesthetext
representation
ofthe
specified64
bitunsigned
integervalue,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineString, Object

Writesthetext
representation
ofthe
specified
object,
followedby
thecurrent
line
terminator,to
thestandard

outputstream
usingthe
specified
format
information.
WriteLineString, Object[]

Writesthetext
representation
ofthe
specifiedarray
ofobjects,
followedby
thecurrent
line
terminator,to
thestandard
outputstream
usingthe
specified
format
information.

WriteLineChar[], Int32, Int32

Writesthe
specified
subarrayof
Unicode
characters,
followedby
thecurrent
line
terminator,to
thestandard
outputstream.

WriteLineString, Object, Object

Writesthetext
representation
ofthe
specified
objects,
followedby
thecurrent
line
terminator,to
thestandard

outputstream
usingthe
specified
format
information.
WriteLineString, Object, Object, Object

Writesthetext
representation
ofthe
specified
objects,
followedby
thecurrent
line
terminator,to
thestandard
outputstream
usingthe
specified
format
information.

WriteLineString, Object, Object, Object, Object

Writesthetext
representation
ofthe
specified
objectsand
variable
length
parameterlist,
followedby
thecurrent
line
terminator,to
thestandard
outputstream
usingthe
specified
format
information.

Thefollowingexampledemonstratesreadingfromconsoleandwritingintoit

Example

openSystem
letmain()=
Console.Write("What'syourname?")
letname=Console.ReadLine()
Console.Write("Hello,{0}\n",name)
Console.WriteLine(System.String.Format("BigGreetingsfrom{0}and{1}",
"TutorialsPoint","AbsoulteClasses"))
Console.WriteLine(System.String.Format("|{0:yyyyMMMdd}|",System.DateTime.Now))
main()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
What'syourname?Kabir
Hello,Kabir
BigGreetingsfromTutorialsPointandAbsoulteClasses
|2015Jan05|

TheSystem.IONamespace
TheSystem.IOnamespacecontainsavarietyofusefulclassesforperformingbasicI/O.
Itcontainstypesorclassesthatallowreadingandwritingtofilesanddatastreamsandtypesthatprovide
basicfileanddirectorysupport.
Classesusefulforworkingwiththefilesystem
TheSystem.IO.Fileclassisusedforcreating,appending,anddeletingfiles.
System.IO.Directoryclassisusedforcreating,moving,anddeletingdirectories.
System.IO.Pathclassperformsoperationsonstrings,whichrepresentfilepaths.
System.IO.FileSystemWatcherclassallowsuserstolistentoadirectoryforchanges.
Classesusefulforworkingwiththestreamssequenceofbytes
System.IO.StreamReaderclassisusedtoreadcharactersfromastream.
System.IO.StreamWriterclassisusedtowritecharacterstoastream.
System.IO.MemoryStreamclasscreatesaninmemorystreamofbytes.
Thefollowingtableshowsalltheclassesprovidedinthenamespacealongwithabriefdescription

Class

Description

BinaryReader

Readsprimitivedatatypesasbinaryvaluesinaspecific
encoding.

BinaryWriter

Writesprimitivetypesinbinarytoastreamandsupports
writingstringsinaspecificencoding.

BufferedStream

Addsabufferinglayertoreadandwriteoperationson
anotherstream.

Directory

Exposesstaticmethodsforcreating,moving,and
enumeratingthroughdirectoriesandsubdirectories.

DirectoryInfo

Exposesinstancemethodsforcreating,moving,and
enumeratingthroughdirectoriesandsubdirectories.

DirectoryNotFoundException

Theexceptionthatisthrownwhenpartofafileordirectory
cannotbefound.

DriveInfo

Providesaccesstoinformationonadrive.

DriveNotFoundException

Theexceptionthatisthrownwhentryingtoaccessadriveor
sharethatisnotavailable.

EndOfStreamException

Theexceptionthatisthrownwhenreadingisattemptedpast
theendofastream.

ErrorEventArgs

ProvidesdatafortheFileSystemWatcher.Errorevent.

File

Providesstaticmethodsforthecreation,copying,deletion,
moving,andopeningofasinglefile,andaidsinthecreation
ofFileStreamobjects.

FileFormatException

Theexceptionthatisthrownwhenaninputfileoradata
streamthatissupposedtoconformtoacertainfileformat
specificationismalformed.

FileInfo

Providespropertiesandinstancemethodsforthecreation,
copying,deletion,moving,andopeningoffiles,andaidsin
thecreationofFileStreamobjects.

FileLoadException

Theexceptionthatisthrownwhenamanagedassemblyis
foundbutcannotbeloaded.

FileNotFoundException

Theexceptionthatisthrownwhenanattempttoaccessafile
thatdoesnotexistondiskfails.

FileStream

ExposesaStreamaroundafile,supportingbothsynchronous
andasynchronousreadandwriteoperations.

FileSystemEventArgs

ProvidesdataforthedirectoryeventsChanged,Created,
Deleted.

FileSystemInfo

ProvidesthebaseclassforbothFileInfoandDirectoryInfo
objects.

FileSystemWatcher

Listenstothefilesystemchangenotificationsandraises

eventswhenadirectory,orfileinadirectory,changes.
InternalBufferOverflowException

Theexceptionthrownwhentheinternalbufferoverflows.

InvalidDataException

Theexceptionthatisthrownwhenadatastreamisinan
invalidformat.

IODescriptionAttribute

Setsthedescriptionvisualdesignerscandisplaywhen
referencinganevent,extender,orproperty.

IOException

TheexceptionthatisthrownwhenanI/Oerroroccurs.

MemoryStream

Createsastreamwhosebackingstoreismemory.

Path

PerformsoperationsonStringinstancesthatcontainfileor
directorypathinformation.Theseoperationsareperformed
inacrossplatformmanner.

PathTooLongException

Theexceptionthatisthrownwhenapathorfilenameis
longerthanthesystemdefinedmaximumlength.

PipeException

Thrownwhenanerroroccurswithinanamedpipe.

RenamedEventArgs

ProvidesdatafortheRenamedevent.

Stream

Providesagenericviewofasequenceofbytes.Thisisan
abstractclass.

StreamReader

ImplementsaTextReaderthatreadscharactersfromabyte
streaminaparticularencoding.

StreamWriter

ImplementsaTextWriterforwritingcharacterstoastream
inaparticularencoding.Tobrowsethe.NETFramework
sourcecodeforthistype,seetheReferenceSource.

StringReader

ImplementsaTextReaderthatreadsfromastring.

StringWriter

ImplementsaTextWriterforwritinginformationtoastring.
TheinformationisstoredinanunderlyingStringBuilder.

TextReader

Representsareaderthatcanreadasequentialseriesof
characters.

TextWriter

Representsawriterthatcanwriteasequentialseriesof
characters.Thisclassisabstract.

UnmanagedMemoryAccessor

Providesrandomaccesstounmanagedblocksofmemory

frommanagedcode.
UnmanagedMemoryStream

Providesaccesstounmanagedblocksofmemoryfrom
managedcode.

WindowsRuntimeStorageExtensions

ContainsextensionmethodsfortheIStorageFileand
IStorageFolderinterfacesintheWindowsRuntimewhen
developingWindowsStoreapps.

WindowsRuntimeStreamExtensions

Containsextensionmethodsforconvertingbetweenstreams
intheWindowsRuntimeandmanagedstreamsinthe.NET
forWindowsStoreapps.

Example
Thefollowingexamplecreatesafilecalledtest.txt,writesamessagethere,readsthetextfromthefile
andprintsitontheconsole.
NoteTheamountofcodeneededtodothisissurprisinglyless!
openSystem.IO//Namespacescanbeopenedjustasmodules
File.WriteAllText("test.txt","HelloThere\nWelcometo:\nTutorialsPoint")
letmsg=File.ReadAllText("test.txt")
printfn"%s"msg

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
HelloThere
Welcometo:
TutorialsPoint

F#GENERICS
Genericsallowyoutodelaythespecificationofthedatatypeofprogrammingelementsinaclassora
method,untilitisactuallyusedintheprogram.Inotherwords,genericsallowyoutowriteaclassor
methodthatcanworkwithanydatatype.
Youwritethespecificationsfortheclassorthemethod,withsubstituteparametersfordatatypes.When
thecompilerencountersaconstructorfortheclassorafunctioncallforthemethod,itgeneratescodeto
handlethespecificdatatype.
InF#,functionvalues,methods,properties,andaggregatetypessuchasclasses,records,and
discriminatedunionscanbegeneric.
Genericconstructscontainatleastonetypeparameter.Genericfunctionsandtypesenableyoutowrite
codethatworkswithavarietyoftypeswithoutrepeatingthecodeforeachtype.

Syntax
Syntaxforwritingagenericconstructisasfollows

//Explicitlygenericfunction.
letfunctionname<typeparameters>parameterlist=
functionbody
//Explicitlygenericmethod.
[static]memberobjectidentifer.methodname<typeparameters>parameterlist[return
type]=
methodbody
//Explicitlygenericclass,record,interface,structure,
//ordiscriminatedunion.
typetypename<typeparameters>typedefinition

Examples
(*GenericFunction*)
letprintFunc<'T>xy=
printfn"%A,%A"xy
printFunc<float>10.020.0

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
10.0,20.0

Youcanalsomakeafunctiongenericbyusingthesinglequotationmarksyntax
(*GenericFunction*)
letprintFunction(x:'a)(y:'a)=
printfn"%A%A"xy
printFunction10.020.0

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
10.020.0

Pleasenotethatwhenyouusegenericfunctionsormethods,youmightnothavetospecifythetype
arguments.However,incaseofanambiguity,youcanprovidetypeargumentsinanglebracketsaswe
didinthefirstexample.
Ifyouhavemorethanonetype,thenyouseparatemultipletypeargumentswithcommas.

GenericClass
Likegenericfunctions,youcanalsowritegenericclasses.Thefollowingexampledemonstratesthis
typegenericClass<'a>(x:'a)=
doprintfn"%A"x
letgr=newgenericClass<string>("zara")
letgs=genericClass(seq{foriin1..10>(i,i*i)})

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

F#DELEGATES
Adelegateisareferencetypevariablethatholdsthereferencetoamethod.Thereferencecanbe
changedatruntime.F#delegatesaresimilartopointerstofunctions,inCorC++.

DeclaringDelegates
Delegatedeclarationdeterminesthemethodsthatcanbereferencedbythedelegate.Adelegatecan
refertoamethod,whichhavethesamesignatureasthatofthedelegate.
Syntaxfordelegatedeclarationis
typedelegatetypename=delegateoftype1>type2

Forexample,considerthedelegates
//Delegate1workswithtuplearguments.
typeDelegate1=delegateof(int*int)>int
//Delegate2workswithcurriedarguments.
typeDelegate2=delegateofint*int>int

Boththedelegatescanbeusedtoreferenceanymethodthathastwointparametersandreturnsanint
typevariable.
Inthesyntax
type1representstheargumenttypes.
type2representsthereturntype.
Pleasenote
Theargumenttypesareautomaticallycurried.
Delegatescanbeattachedtofunctionvalues,andstaticorinstancemethods.
F#functionvaluescanbepasseddirectlyasargumentstodelegateconstructors.
Forastaticmethodthedelegateiscalledbyusingthenameoftheclassandthemethod.Foran
instancemethod,thenameoftheobjectinstanceandmethodisused.
TheInvokemethodonthedelegatetypecallstheencapsulatedfunction.
Also,delegatescanbepassedasfunctionvaluesbyreferencingtheInvokemethodnamewithout
theparentheses.
Thefollowingexampledemonstratestheconcept

Example

typeMyclass()=
staticmemberadd(a:int,b:int)=
a+b
staticmembersub(a:int)(b:int)=
ab
memberx.Add(a:int,b:int)=
a+b
memberx.Sub(a:int)(b:int)=
ab
//Delegate1workswithtuplearguments.
typeDelegate1=delegateof(int*int)>int
//Delegate2workswithcurriedarguments.
typeDelegate2=delegateofint*int>int
letInvokeDelegate1(dlg:Delegate1)(a:int)(b:int)=
dlg.Invoke(a,b)
letInvokeDelegate2(dlg:Delegate2)(a:int)(b:int)=
dlg.Invoke(a,b)
//Forstaticmethods,usetheclassname,thedotoperator,andthe
//nameofthestaticmethod.
letdel1:Delegate1=newDelegate1(Myclass.add)
letdel2:Delegate2=newDelegate2(Myclass.sub)
letmc=Myclass()
//Forinstancemethods,usetheinstancevaluename,thedotoperator,andtheinstance
methodname.
letdel3:Delegate1=newDelegate1(mc.Add)
letdel4:Delegate2=newDelegate2(mc.Sub)
for(a,b)in[(400,200);(100,45)]do
printfn"%d+%d=%d"ab(InvokeDelegate1del1ab)
printfn"%d%d=%d"ab(InvokeDelegate2del2ab)
printfn"%d+%d=%d"ab(InvokeDelegate1del3ab)
printfn"%d%d=%d"ab(InvokeDelegate2del4ab)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
400+200=600
400200=200
400+200=600
400200=200
100+45=145
10045=55
100+45=145
10045=55

F#ENUMERATIONS
Anenumerationisasetofnamedintegerconstants.
InF#,enumerations,alsoknownasenums,areintegraltypeswherelabelsareassignedtoasubsetof
thevalues.Youcanusetheminplaceofliteralstomakecodemorereadableandmaintainable.

DeclaringEnumerations
Thegeneralsyntaxfordeclaringanenumerationis
typeenumname=
|value1=integerliteral1
|value2=integerliteral2
...

Thefollowingexampledemonstratestheuseofenumerations

Example
//Declarationofanenumeration.
typeDays=
|Sun=0
|Mon=1
|Tues=2
|Wed=3
|Thurs=4
|Fri=5
|Sat=6
//Useofanenumeration.
letweekend1:Days=Days.Sat
letweekend2:Days=Days.Sun
letweekDay1:Days=Days.Mon
printfn"Monday:%A"weekDay1
printfn"Saturday:%A"weekend1
printfn"Sunday:%A"weekend2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Monday:Mon
Saturday:Sat
Sunday:Sun

F#PATTERNMATCHING
Patternmatchingallowsyoutocomparedatawithalogicalstructureorstructures,decomposedata
intoconstituentparts,orextractinformationfromdatainvariousways.
Inotherterms,itprovidesamoreflexibleandpowerfulwayoftestingdataagainstaseriesofconditions
andperformingsomecomputationsbasedontheconditionmet.
Conceptually,itislikeaseriesofifthenstatements.

Syntax
Inhighlevelterms,patternmatchingfollowsthissyntaxinF#
matchexprwith
|pat1result1

|pat2>result2
|pat3whenexpr2>result3
|_>defaultResult

Where,
Each|symboldefinesacondition.
The>symbolmeans"iftheconditionistrue,returnthisvalue...".
The_symbolprovidesthedefaultpattern,meaningthatitmatchesallotherthingslikea
wildcard.

Example1
Thefollowingexample,calculatestheFibonaccinumbersusingpatternmatchingsyntax
letrecfibn=
matchnwith
|0>0
|1>1
|_>fib(n1)+fib(n2)
fori=1to10do
printfn"Fibonacci%d:%d"i(fibi)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Fibonacci1:1
Fibonacci2:1
Fibonacci3:2
Fibonacci4:3
Fibonacci5:5
Fibonacci6:8
Fibonacci7:13
Fibonacci8:21
Fibonacci9:34
Fibonacci10:55

Youcanalsochaintogethermultipleconditions,whichreturnthesamevalue.Forexample

Example2
letprintSeasonmonth=
matchmonthwith
|"December"|"January"|"February">printfn"Winter"
|"March"|"April">printfn"Spring"
|"May"|"June">printfn"Summer"
|"July"|"August">printfn"Rainy"
|"September"|"October"|"November">printfn"Autumn"
|_>printfn"Seasondependsonmonth!"
printSeason"February"
printSeason"April"
printSeason"November"
printSeason"July"

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Winter
Spring
Autumn
Rainy

PatternMatchingFunctions
F#allowsyoutowritepatternmatchingfunctionsusingthefunctionkeyword
letgetRate=function
|"potato">10.00
|"brinjal">20.50
|"cauliflower">21.00
|"cabbage">8.75
|"carrot">15.00
|_>nan(*nanisaspecialvaluemeaning"notanumber"*)
printfn"%g"(getRate"potato")
printfn"%g"(getRate"brinjal")
printfn"%g"(getRate"cauliflower")
printfn"%g"(getRate"cabbage")
printfn"%g"(getRate"carrot")

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
10
20.5
21
8.75
15

AddingFiltersorGuardstoPatterns
Youcanaddfilters,orguards,topatternsusingthewhenkeyword.

Example1
letsign=function
|0>0
|xwhenx<0>1
|xwhenx>0>1
printfn"%d"(sign20)
printfn"%d"(sign20)
printfn"%d"(sign0)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
1
1
0

Example2
letcompareIntx=
matchxwith
|(var1,var2)whenvar1>var2>printfn"%disgreaterthan%d"var1var2
|(var1,var2)whenvar1<var2>printfn"%dislessthan%d"var1var2
|(var1,var2)>printfn"%dequals%d"var1var2
compareInt(11,25)
compareInt(72,10)
compareInt(0,0)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
11islessthan25
72isgreaterthan10
0equals0

PatternMatchingwithTuples
Thefollowingexampledemonstratesthepatternmatchingwithtuples
letgreeting(name,subject)=
match(name,subject)with
|("Zara",_)>"Hello,Zara"
|(name,"English")>"Hello,"+name+"fromthedepartmentofEnglish"
|(name,_)whensubject.StartsWith("Comp")>"Hello,"+name+"fromthe
departmentofComputerSc."
|(_,"AccountsandFinance")>"WelcometothedepartmentofAccountsandFinance!"
|_>"Youarenotregisteredintothesystem"
printfn"%s"(greeting("Zara","English"))
printfn"%s"(greeting("Raman","ComputerScience"))
printfn"%s"(greeting("Ravi","Mathematics"))

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Hello,Zara
Hello,RamanfromthedepartmentofComputerSc.
Youarenotregisteredintothesystem

PatternMatchingwithRecords
Thefollowingexampledemonstratespatternmatchingwithrecords
typePoint={x:float;y:float}
letevaluatePoint(point:Point)=
matchpointwith
|{x=0.0;y=0.0}>printfn"Pointisattheorigin."
|{x=xVal;y=0.0}>printfn"Pointisonthexaxis.Valueis%f."xVal
|{x=0.0;y=yVal}>printfn"Pointisontheyaxis.Valueis%f."yVal
|{x=xVal;y=yVal}>printfn"Pointisat(%f,%f)."xValyVal
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}

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Pointisattheorigin.
Pointisonthexaxis.Valueis10.000000.
Pointisontheyaxis.Valueis10.000000.
Pointisat(10.000000,10.000000).

F#EXCEPTIONHANDLING
Anexceptionisaproblemthatarisesduringtheexecutionofaprogram.AnF#exceptionisaresponseto
anexceptionalcircumstancethatariseswhileaprogramisrunning,suchasanattempttodividebyzero.
Exceptionsprovideawaytotransfercontrolfromonepartofaprogramtoanother.F#exception
handlingprovidesthefollowingconstructs

Construct

Description

raiseexpr

Raisesthegivenexception.

failwithexpr

RaisestheSystem.Exceptionexception.

tryexprwithrules

Catchesexpressionsmatchingthepatternrules.

tryexprfinallyexpr

Executionthefinallyexpressionbothwhenthecomputationis
successfulandwhenanexceptionisraised.

|:?ArgumentException

Arulematchingthegiven.NETexceptiontype.

|:?ArgumentExceptionase

Arulematchingthegiven.NETexceptiontype,bindingthename
etotheexceptionobjectvalue.

|Failuremsgexpr

ArulematchingthegivendatacarryingF#exception.

|exnexpr

Arulematchinganyexception,bindingthenameexntothe
exceptionobjectvalue.

|exnwhenexprexpr

Arulematchingtheexceptionunderthegivencondition,binding
thenameexntotheexceptionobjectvalue.

LetusstartwiththebasicsyntaxofExceptionHandling.

Syntax
BasicsyntaxforF#exceptionhandlingblockis

exceptionexceptiontypeofargumenttype

Where,
exceptiontypeisthenameofanewF#exceptiontype.
argumenttyperepresentsthetypeofanargumentthatcanbesuppliedwhenyouraisean
exceptionofthistype.
Multipleargumentscanbespecifiedbyusingatupletypeforargumenttype.
Thetry...withexpressionisusedforexceptionhandlingintheF#language.
Syntaxforthetrywithexpressionis
try
expression1
with
|pattern1>expression2
|pattern2>expression3
...

Thetry...finallyexpressionallowsyoutoexecutecleanupcodeevenifablockofcodethrowsan
exception.
Syntaxforthetryfinallyexpressionis
try
expression1
finally
expression2

Theraisefunctionisusedtoindicatethatanerrororexceptionalconditionhasoccurred.Italso
capturestheinformationabouttheerrorinanexceptionobject.
Syntaxfortheraisefunctionis
raise(expression)

ThefailwithfunctiongeneratesanF#exception.
Syntaxforthefailwithfunctionis
failwitherrormessagestring

TheinvalidArgfunctiongeneratesanargumentexception.
invalidArgparameternameerrormessagestring

ExampleofExceptionHandling
Example1

Thefollowingprogramshowsthebasicexceptionhandlingwithasimpletrywithblock
letdivisionprogxy=
try
Some(x/y)
with
|:?System.DivideByZeroException>printfn"Divisionbyzero!";None
letresult1=divisionprog1000

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Divisionbyzero!

Example2
F#providesanexceptiontypefordeclaringexceptions.Youcanuseanexceptiontypedirectlyinthe
filtersinatry...withexpression.
Thefollowingexampledemonstratesthis
exceptionError1ofstring
//Usingatupletypeastheargumenttype.
exceptionError2ofstring*int
letmyfunctionxy=
try
ifx=ythenraise(Error1("EqualNumberError"))
elseraise(Error2("ErrorNotdetected",100))
with
|Error1(str)>printfn"Error1%s"str
|Error2(str,i)>printfn"Error2%s%d"stri
myfunction2010
myfunction55

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Error2ErrorNotdetected100
Error1EqualNumberError

Example3
Thefollowingexampledemonstratesnestedexceptionhandling
exceptionInnerErrorofstring
exceptionOuterErrorofstring
letfunc1xy=
try
try
ifx=ythenraise(InnerError("innererror"))
elseraise(OuterError("outererror"))
with
|InnerError(str)>printfn"Error:%s"str

finally
printfn"Fromthefinallyblock."
letfunc2xy=
try
func1xy
with
|OuterError(str)>printfn"Error:%s"str
func2100150
func2100100
func2100120

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Fromthefinallyblock.
Error:outererror
Error:innererror
Fromthefinallyblock.
Fromthefinallyblock.
Error:outererror

Example4
Thefollowingfunctiondemonstratesthefailwithfunction
letdivisionFuncxy=
if(y=0)thenfailwith"Divisorcannotbezero."
else
x/y
lettrydivisionFuncxy=
try
divisionFuncxy
with
|Failure(msg)>printfn"%s"msg;0
letresult1=trydivisionFunc1000
letresult2=trydivisionFunc1004
printfn"%A"result1
printfn"%A"result2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Divisorcannotbezero.
0
25

Example5
TheinvalidArgfunctiongeneratesanargumentexception.Thefollowingprogramdemonstratesthis
letdays=[|"Sunday";"Monday";"Tuesday";"Wednesday";"Thursday";"Friday";
"Saturday"|]

letfindDayday=
if(day>7||day<1)
theninvalidArg"day"(sprintf"Youhaveentered%d."day)
days.[day1]
printfn"%s"(findDay1)
printfn"%s"(findDay5)
printfn"%s"(findDay9)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Sunday
Thursday
UnhandledException:
System.ArgumentException:Youhaveentered9.

Someotherinformationaboutthefileandvariablecausingerrorinthesystemwillalsobedisplayed,
dependinguponthesystem.

F#CLASSES
Classesaretypesthatrepresentobjectsthatcanhaveproperties,methods,andevents.Theyareusedto
modelactions,processes,andanyconceptualentitiesinapplications.

Syntax
Syntaxfordefiningaclasstypeisasfollows
//Classdefinition:
type[accessmodifier]typename[typeparams][accessmodifier](parameterlist)[as
identifier]=
[class]
[inheritbasetypename(baseconstructorargs)]
[letbindings]
[dobindings]
memberlist
...
[end]
//Mutuallyrecursiveclassdefinitions:
type[accessmodifier]typename1...
and[accessmodifier]typename2...
...

Where,
Thetypenameisanyvalididentifier.Defaultaccessmodifierforthisispublic.
Thetypeparamsdescribesoptionalgenerictypeparameters.
Theparameterlistdescribesconstructorparameters.Defaultaccessmodifierforprimary
constructorispublic.
Theidentifierusedwiththeoptionalaskeywordgivesanametotheinstancevariable,orself

identifier,whichcanbeusedinthetypedefinitiontorefertotheinstanceofthetype.
Theinheritkeywordallowsyoutospecifythebaseclassforaclass.
Theletbindingsallowyoutodeclarefieldsorfunctionvalueslocaltotheclass.
Thedobindingssectionincludescodetobeexecuteduponobjectconstruction.
Thememberlistconsistsofadditionalconstructors,instanceandstaticmethoddeclarations,
interfacedeclarations,abstractbindings,andpropertyandeventdeclarations.
Thekeywordsclassandendthatmarkthestartandendofthedefinitionareoptional.

ConstructorofaClass
Theconstructoriscodethatcreatesaninstanceoftheclasstype.
InF#,constructorsworklittledifferentlythanother.Netlanguages.Intheclassdefinition,the
argumentsoftheprimaryconstructoraredescribedasparameterlist.
Thebodyoftheconstructorconsistsoftheletanddobindings.
Youcanaddadditionalconstructorsbyusingthenewkeywordtoaddamember
new(argumentlist)=constructorbody

Thefollowingexampleillustratestheconcept

Example
Thefollowingprogramcreatesalineclassalongwithaconstructorthatcalculatesthelengthoftheline
whileanobjectoftheclassiscreated
typeLine=class
valX1:float
valY1:float
valX2:float
valY2:float
new(x1,y1,x2,y2)asthis=
{X1=x1;Y1=y1;X2=x2;Y2=y2;}
then
printfn"CreatingLine:{(%g,%g),(%g,%g)}\nLength:%g"
this.X1this.Y1this.X2this.Y2this.Length
memberx.Length=
letsqrx=x*x
sqrt(sqr(x.X1x.X2)+sqr(x.Y1x.Y2))
end
letaLine=newLine(1.0,1.0,4.0,5.0)

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
CreatingLine:{(1,1),(4,5)}
Length:5

LetBindings
TheletbindingsinaclassdefinitionallowyoutodefineprivatefieldsandprivatefunctionsforF#
classes.
typeGreetings(name)asgr=
letdata=name
do
gr.PrintMessage()
memberthis.PrintMessage()=
printf"Hello%s\n"data
letgtr=newGreetings("Zara")

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
HelloZara

PleasenotetheuseofselfidentifiergrfortheGreetingsclass.

F#STRUCTURES
AstructureinF#isavaluetypedatatype.Ithelpsyoutomakeasinglevariable,holdrelateddataof
variousdatatypes.Thestructkeywordisusedforcreatingastructure.

Syntax
Syntaxfordefiningastructureisasfollows
[attributes]
type[accessibilitymodifier]typename=
struct
typedefinitionelements
end
//or
[attributes]
[<StructAttribute>]
type[accessibilitymodifier]typename=
typedefinitionelements

Therearetwosyntaxes.Thefirstsyntaxismostlyused,because,ifyouusethestructandend
keywords,youcanomittheStructAttributeattribute.
Thestructuredefinitionelementsprovide
Memberdeclarationsanddefinitions.
Constructorsandmutableandimmutablefields.
Membersandinterfaceimplementations.
Unlikeclasses,structurescannotbeinheritedandcannotcontainletordobindings.Since,structuresdo
nothaveletbindingsyoumustdeclarefieldsinstructuresbyusingthevalkeyword.
Whenyoudefineafieldanditstypeusingvalkeyword,youcannotinitializethefieldvalue,insteadthey
areinitializedtozeroornull.Soforastructurehavinganimplicitconstructor,thevaldeclarationsbe

annotatedwiththeDefaultValueattribute.

Example
Thefollowingprogramcreatesalinestructurealongwithaconstructor.Theprogramcalculatesthe
lengthofalineusingthestructure
typeLine=struct
valX1:float
valY1:float
valX2:float
valY2:float
new(x1,y1,x2,y2)=
{X1=x1;Y1=y1;X2=x2;Y2=y2;}
end
letcalcLength(a:Line)=
letsqra=a*a
sqrt(sqr(a.X1a.X2)+sqr(a.Y1a.Y2))
letaLine=newLine(1.0,1.0,4.0,5.0)
letlength=calcLengthaLine
printfn"LengthoftheLine:%g"length

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
LengthoftheLine:5

F#OPERATOROVERLOADING
YoucanredefineoroverloadmostofthebuiltinoperatorsavailableinF#.Thusaprogrammercanuse
operatorswithuserdefinedtypesaswell.
Operatorsarefunctionswithspecialnames,enclosedinbrackets.Theymustbedefinedasstaticclass
members.Likeanyotherfunction,anoverloadedoperatorhasareturntypeandaparameterlist.
Thefollowingexample,showsa+operatoroncomplexnumbers
//overloading+operator
staticmember(+)(a:Complex,b:Complex)=
Complex(a.x+b.x,a.y+b.y)

Theabovefunctionimplementstheadditionoperator + forauserdefinedclassComplex.Itaddsthe
attributesoftwoobjectsandreturnstheresultantComplexobject.

ImplementationofOperatorOverloading
Thefollowingprogramshowsthecompleteimplementation
//implementingacomplexclasswith+,andoperators
//overloaded
typeComplex(x:float,y:float)=
memberthis.x=x
memberthis.y=y
//overloading+operator

staticmember(+)(a:Complex,b:Complex)=
Complex(a.x+b.x,a.y+b.y)
//overloadingoperator
staticmember()(a:Complex,b:Complex)=
Complex(a.xb.x,a.yb.y)
//overridingtheToStringmethod
overridethis.ToString()=
this.x.ToString()+""+this.y.ToString()
//Creatingtwocomplexnumbers
letc1=Complex(7.0,5.0)
letc2=Complex(4.2,3.1)
//additionandsubtractionusingthe
//overloadedoperators
letc3=c1+c2
letc4=c1c2
//printingthecomplexnumbers
printfn"%s"(c1.ToString())
printfn"%s"(c2.ToString())
printfn"%s"(c3.ToString())
printfn"%s"(c4.ToString())

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
75
4.23.1
11.28.1
2.81.9

F#INHERITANCE
Oneofthemostimportantconceptsinobjectorientedprogrammingisthatofinheritance.Inheritance
allowsustodefineaclassintermsofanotherclass,whichmakesiteasiertocreateandmaintainan
application.Thisalsoprovidesanopportunitytoreusethecodefunctionalityandfastimplementation
time.
Whencreatingaclass,insteadofwritingcompletelynewdatamembersandmemberfunctions,the
programmercandesignatethatthenewclassshouldinheritthemembersofanexistingclass.This
existingclassiscalledthebaseclass,andthenewclassisreferredtoasthederivedclass.
TheideaofinheritanceimplementstheISArelationship.Forexample,mammalISAanimal,dogISA
mammalhencedogISAanimalaswellandsoon.

BaseClassandSubClass
Asubclassisderivedfromabaseclass,whichisalreadydefined.Asubclassinheritsthemembersofthe
baseclass,aswellashasitsownmembers.
Asubclassisdefinedusingtheinheritkeywordasshownbelow
typeMyDerived(...)=
inheritMyBase(...)

InF#,aclasscanhaveatmostonedirectbaseclass.Ifyoudonotspecifyabaseclassbyusingthe
inheritkeyword,theclassimplicitlyinheritsfromObject.
Pleasenote
Themethodsandmembersofthebaseclassareavailabletousersofthederivedclasslikethe
directmembersofthederivedclass.
Letbindingsandconstructorparametersareprivatetoaclassand,therefore,cannotbeaccessed
fromderivedclasses.
Thekeywordbasereferstothebaseclassinstance.Itisusedliketheselfidentifier.

Example
typePerson(name)=
memberx.Name=name
memberx.Greet()=printfn"Hi,I'm%s"x.Name
typeStudent(name,studentID:int)=
inheritPerson(name)
letmutable_GPA=0.0
memberx.StudentID=studentID
memberx.GPA
withget()=_GPA
andsetvalue=_GPA<value
typeTeacher(name,expertise:string)=
inheritPerson(name)
letmutable_salary=0.0
memberx.Salary
withget()=_salary
andsetvalue=_salary<value
memberx.Expertise=expertise
//usingthesubclasses
letp=newPerson("Mohan")
letst=newStudent("Zara",1234)
lettr=newTeacher("Mariam","Java")
p.Greet()
st.Greet()
tr.Greet()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Hi,I'mMohan
Hi,I'mZara
Hi,I'mMariam

OverridingMethods
Youcanoverrideadefaultbehaviorofabaseclassmethodandimplementitdifferentlyinthesubclass
orthederivedclass.

MethodsinF#arenotoverridablebydefault.
Tooverridemethodsinaderivedclass,youhavetodeclareyourmethodasoverridableusingthe
abstractanddefaultkeywordsasfollows
typePerson(name)=
memberx.Name=name
abstractGreet:unit>unit
defaultx.Greet()=printfn"Hi,I'm%s"x.Name

Now,theGreetmethodofthePersonclasscanbeoverriddeninderivedclasses.Thefollowingexample
demonstratesthis

Example
typePerson(name)=
memberx.Name=name
abstractGreet:unit>unit
defaultx.Greet()=printfn"Hi,I'm%s"x.Name
typeStudent(name,studentID:int)=
inheritPerson(name)
letmutable_GPA=0.0
memberx.StudentID=studentID
memberx.GPA
withget()=_GPA
andsetvalue=_GPA<value
overridex.Greet()=printfn"Student%s"x.Name
typeTeacher(name,expertise:string)=
inheritPerson(name)
letmutable_salary=0.0
memberx.Salary
withget()=_salary
andsetvalue=_salary<value
memberx.Expertise=expertise
overridex.Greet()=printfn"Teacher%s."x.Name
//usingthesubclasses
letp=newPerson("Mohan")
letst=newStudent("Zara",1234)
lettr=newTeacher("Mariam","Java")
//defaultGreet
p.Greet()
//OverridenGreet
st.Greet()
tr.Greet()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Hi,I'mMohan

StudentZara
TeacherMariam.

AbstractClass
Attimesyouneedtoprovideanincompleteimplementationofanobject,whichshouldnotbe
implementedinreality.Later,someotherprogrammershouldcreatesubclassesoftheabstractclasstoa
completeimplementation.
Forexample,thePersonclasswillnotbeneededinaSchoolManagementSystem.However,theStudent
ortheTeacherclasswillbeneeded.Insuchcases,youcandeclarethePersonclassasanabstractclass.
TheAbstractClassattributetellsthecompilerthattheclasshassomeabstractmembers.
Youcannotcreateaninstanceofanabstractclassbecausetheclassisnotfullyimplemented.
Thefollowingexampledemonstratesthis

Example
[<AbstractClass>]
typePerson(name)=
memberx.Name=name
abstractGreet:unit>unit
typeStudent(name,studentID:int)=
inheritPerson(name)
letmutable_GPA=0.0
memberx.StudentID=studentID
memberx.GPA
withget()=_GPA
andsetvalue=_GPA<value
overridex.Greet()=printfn"Student%s"x.Name
typeTeacher(name,expertise:string)=
inheritPerson(name)
letmutable_salary=0.0
memberx.Salary
withget()=_salary
andsetvalue=_salary<value
memberx.Expertise=expertise
overridex.Greet()=printfn"Teacher%s."x.Name
letst=newStudent("Zara",1234)
lettr=newTeacher("Mariam","Java")
//OverridenGreet
st.Greet()
tr.Greet()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
StudentZara
TeacherMariam.

F#INTERFACES
Interfacesprovideanabstractwayofwritinguptheimplementationdetailsofaclass.Itisatemplate
thatdeclaresthemethodstheclassmustimplementandexposepublicly.

Syntax
Aninterfacespecifiesthesetsofrelatedmembersthatotherclassesimplement.Ithasthefollowing
syntax
//Interfacedeclaration:
[attributes]
typeinterfacename=
[interface]
[inheritbaseinterfacename...]
abstractmember1:[argumenttypes1>]returntype1
abstractmember2:[argumenttypes2>]returntype2
...
[end]

//Implementing,insideaclasstypedefinition:
interfaceinterfacenamewith
memberselfidentifier.member1argumentlist=methodbody1
memberselfidentifier.member2argumentlist=methodbody2
//Implementing,byusinganobjectexpression:
[attributes]
letclassname(argumentlist)=
{newinterfacenamewith
memberselfidentifier.member1argumentlist=methodbody1
memberselfidentifier.member2argumentlist=methodbody2
[baseinterfacedefinitions]
}
memberlist

Pleasenote
Inaninterfacedeclarationthemembersarenotimplemented.
Themembersareabstract,declaredbytheabstractkeyword.Howeveryoumayprovidea
defaultimplementationusingthedefaultkeyword.
Youcanimplementinterfaceseitherbyusingobjectexpressionsorbyusingclasstypes.
Inclassorobjectimplementation,youneedtoprovidemethodbodiesforabstractmethodsofthe
interface.
Thekeywordsinterfaceandend,whichmarkthestartandendofthedefinition,areoptional.
Forexample,
typeIPerson=
abstractName:string
abstractEnter:unit>unit
abstractLeave:unit>unit

CallingInterfaceMethods
Interfacemethodsarecalledthroughtheinterface,notthroughtheinstanceoftheclassortype
implementinginterface.Tocallaninterfacemethod,youupcasttotheinterfacetypebyusingthe:>
operatorupcastoperator.
Forexample,
(s:>IPerson).Enter()
(s:>IPerson).Leave()

Thefollowingexampleillustratestheconcept

Example
typeIPerson=
abstractName:string
abstractEnter:unit>unit
abstractLeave:unit>unit
typeStudent(name:string,id:int)=
memberthis.ID=id
interfaceIPersonwith
memberthis.Name=name
memberthis.Enter()=printfn"Studententeringpremises!"
memberthis.Leave()=printfn"Studentleavingpremises!"
typeStuffMember(name:string,id:int,salary:float)=
letmutable_salary=salary
memberthis.Salary
withget()=_salary
andset(value)=_salary<value
interfaceIPersonwith
memberthis.Name=name
memberthis.Enter()=printfn"Stuffmemberenteringpremises!"
memberthis.Leave()=printfn"Stuffmemberleavingpremises!"
lets=newStudent("Zara",1234)
letst=newStuffMember("Rohit",34,50000.0)
(s:>IPerson).Enter()
(s:>IPerson).Leave()
(st:>IPerson).Enter()
(st:>IPerson).Leave()

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Studententeringpremises!
Studentleavingpremises!
Stuffmemberenteringpremises!
Stuffmemberleavingpremises!

InterfaceInheritance

Interfacescaninheritfromoneormorebaseinterfaces.
Thefollowingexampleshowstheconcept
typeInterface1=
abstractmemberdoubleIt:int>int
typeInterface2=
abstractmembertripleIt:int>int
typeInterface3=
inheritInterface1
inheritInterface2
abstractmemberprintIt:int>string
typemultiplierClass()=
interfaceInterface3with
memberthis.doubleIt(a)=2*a
memberthis.tripleIt(a)=3*a
memberthis.printIt(a)=a.ToString()
letml=multiplierClass()
printfn"%d"((ml:>Interface3).doubleIt(5))
printfn"%d"((ml:>Interface3).tripleIt(5))
printfn"%s"((ml:>Interface3).printIt(5))

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
10
15
5

F#EVENTS
Eventsallowclassestosendandreceivemessagesbetweenoneanother.
InGUI,eventsareuseractionslikekeypress,clicks,mousemovements,etc.,orsomeoccurrencelike
systemgeneratednotifications.Applicationsneedtorespondtoeventswhentheyoccur.Forexample,
interrupts.Eventsareusedforinterprocesscommunication.
Objectscommunicatewithoneanotherthroughsynchronousmessagepassing.
Eventsareattachedtootherfunctionsobjectsregistercallbackfunctionstoanevent,andthese
callbacksareexecutedwhenandiftheeventistriggeredbysomeobject.

TheEventClassandEventModule
TheControl.Event<'T>Classhelpsincreatinganobservableobjectorevent.
Ithasthefollowinginstancememberstoworkwiththeevents

Member

Description

Publish

Publishesanobservationasafirstclassvalue.

Trigger

Triggersanobservationusingthegivenparameters.

TheControl.EventModuleprovidesfunctionsformanagingeventstreams

Value

Description

add: T unitEvent<'Del,'T>unit

Runsthegivenfunctioneachtimethegiveneventis
triggered.

choose: T UoptionIEvent<'Del,'T>
IEvent<'U>

Returnsaneweventwhichfiresonaselectionof
messagesfromtheoriginalevent.Theselection
functiontakesanoriginalmessagetoanoptional
newmessage.

filter: T boolIEvent<'Del,'T>
IEvent<'T>

Returnsaneweventthatlistenstotheoriginal
eventandtriggerstheresultingeventonlywhen
theargumenttotheeventpassesthegiven
function.

map: T UIEvent<'Del,'T>
IEvent<'U>

Returnsaneweventthatpassesvalues
transformedbythegivenfunction.

merge:IEvent<'Del1,'T>IEvent<'Del2,'T>
IEvent<'T>

Firestheoutputeventwheneitheroftheinput
eventsfire.

pairwise:IEvent<'Del,'T>IEvent<'T*'T>

Returnsaneweventthattriggersonthesecond
andsubsequenttriggeringoftheinputevent.The
Nthtriggeringoftheinputeventpassesthe
argumentsfromtheN1thandNthtriggeringasa
pair.TheargumentpassedtotheN1thtriggering
isheldinhiddeninternalstateuntiltheNth
triggeringoccurs.

partition: T boolIEvent<'Del,'T>
IEvent<'T>*IEvent<'T>

Returnsaneweventthatlistenstotheoriginal
eventandtriggersthefirstresultingeventifthe
applicationofthepredicatetotheeventarguments
returnedtrue,andthesecondeventifitreturned
false.

scan: U T U'UIEvent<'Del,'T>
IEvent<'U>

Returnsaneweventconsistingoftheresultsof
applyingthegivenaccumulatingfunctionto
successivevaluestriggeredontheinputevent.An
itemofinternalstaterecordsthecurrentvalueof
thestateparameter.Theinternalstateisnotlocked

duringtheexecutionoftheaccumulationfunction,
socareshouldbetakenthattheinputIEventnot
triggeredbymultiplethreadssimultaneously.
split: T Choice < U1, U2 >
IEvent<'Del,'T>IEvent<'U1>*
IEvent<'U2>

Returnsaneweventthatlistenstotheoriginal
eventandtriggersthefirstresultingeventifthe
applicationofthefunctiontotheeventarguments
returnedaChoice1Of2,andthesecondeventifit
returnsaChoice2Of2.

CreatingEvents
EventsarecreatedandusedthroughtheEventclass.TheEventconstructorisusedforcreatingan
event.

Example
typeWorker(name:string,shift:string)=
letmutable_name=name;
letmutable_shift=shift;
letnameChanged=newEvent<unit>()(*createsevent*)
letshiftChanged=newEvent<unit>()(*createsevent*)
memberthis.Name
withget()=_name
andset(value)=_name<value
memberthis.Shift
withget()=_shift
andset(value)=_shift<value

AfterthisyouneedtoexposethenameChangedfieldasapublicmember,sothatthelistenerscanhook
ontotheeventforwhich,youusethePublishpropertyoftheevent
typeWorker(name:string,shift:string)=
letmutable_name=name;
letmutable_shift=shift;
letnameChanged=newEvent<unit>()(*createsevent*)
letshiftChanged=newEvent<unit>()(*createsevent*)
memberthis.NameChanged=nameChanged.Publish(*exposedeventhandler*)
memberthis.ShiftChanged=shiftChanged.Publish(*exposedeventhandler*)
memberthis.Name
withget()=_name
andset(value)=_name<value
nameChanged.Trigger()(*invokeseventhandler*)
memberthis.Shift
withget()=_shift

andset(value)=_shift<value
shiftChanged.Trigger()(*invokeseventhandler*)

Next,youaddcallbackstoeventhandlers.EacheventhandlerhasthetypeIEvent<'T>,whichprovides
severalmethods

Method

Description

valAdd:event: T unitunit

Connectsalistenerfunctiontotheevent.Thelistenerwill
beinvokedwhentheeventisfired.

valAddHandler:'delunit

Connectsahandlerdelegateobjecttotheevent.Ahandler
canbelaterremovedusingRemoveHandler.Thelistener
willbeinvokedwhentheeventisfired.

valRemoveHandler:'delunit

Removesalistenerdelegatefromaneventlistenerstore.

Thefollowingsectionprovidesacompleteexample.

Example
Thefollowingexampledemonstratestheconceptandtechniquesdiscussedabove
typeWorker(name:string,shift:string)=
letmutable_name=name;
letmutable_shift=shift;
letnameChanged=newEvent<unit>()(*createsevent*)
letshiftChanged=newEvent<unit>()(*createsevent*)
memberthis.NameChanged=nameChanged.Publish(*exposedeventhandler*)
memberthis.ShiftChanged=shiftChanged.Publish(*exposedeventhandler*)
memberthis.Name
withget()=_name
andset(value)=
_name<value
nameChanged.Trigger()(*invokeseventhandler*)
memberthis.Shift
withget()=_shift
andset(value)=
_shift<value
shiftChanged.Trigger()(*invokeseventhandler*)
letwk=newWorker("Wilson","Evening")
wk.NameChanged.Add(fun()>printfn"Workerchangedname!Newname:%s"wk.Name)
wk.Name<"William"
wk.NameChanged.Add(fun()>printfn"AnotherhandlerattachedtoNameChanged!")
wk.Name<"Bill"
wk.ShiftChanged.Add(fun()>printfn"Workerchangedshift!Newshift:%s"wk.Shift)

wk.Shift<"Morning"
wk.ShiftChanged.Add(fun()>printfn"AnotherhandlerattachedtoShiftChanged!")
wk.Shift<"Night"

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
Workerchangedname!Newname:William
Workerchangedname!Newname:Bill
AnotherhandlerattachedtoNameChanged!
Workerchangedshift!Newshift:Morning
Workerchangedshift!Newshift:Night
AnotherhandlerattachedtoShiftChanged!

F#MODULES
AsperMSDNlibrary,anF#moduleisagroupingofF#codeconstructs,suchastypes,values,function
values,andcodeindobindings.ItisimplementedasacommonlanguageruntimeCLRclassthathasonly
staticmembers.
Dependinguponthesituationwhetherthewholefileisincludedinthemodule,therearetwotypesof
moduledeclarations
Toplevelmoduledeclaration
Localmoduledeclaration
Inatoplevelmoduledeclarationthewholefileisincludedinthemodule.Inthiscase,thefirst
declarationinthefileisthemoduledeclaration.Youdonothavetoindentdeclarationsinatoplevel
module.
Inalocalmoduledeclaration,onlythedeclarationsthatareindentedunderthatmoduledeclarationare
partofthemodule.

Syntax
Syntaxformoduledeclarationisasfollows
//Toplevelmoduledeclaration.
module[accessibilitymodifier][qualifiednamespace.]modulename
declarations
//Localmoduledeclaration.
module[accessibilitymodifier]modulename=
declarations

Pleasenotethattheaccessibilitymodifiercanbeoneofthefollowingpublic,private,internal.The
defaultispublic.
Thefollowingexampleswilldemonstratetheconcepts

Example1
ThemodulefileArithmetic.fs
moduleArithmetic
letaddxy=

x+y
letsubxy=
xy

letmultxy=
x*y

letdivxy=
x/y

Theprogramfilemain.fs
//Fullyqualifythefunctionname.
letaddRes=Arithmetic.add259
letsubRes=Arithmetic.sub259
letmultRes=Arithmetic.mult259
letdivRes=Arithmetic.div259
printfn"%d"addRes
printfn"%d"subRes
printfn"%d"multRes
printfn"%d"divRes
//Openingthemodule.
openArithmetic
letaddRes2=Arithmetic.add10010
letsubRes2=Arithmetic.sub10010
letmultRes2=Arithmetic.mult10010
letdivRes2=Arithmetic.div10010
printfn"%d"addRes2
printfn"%d"subRes2
printfn"%d"multRes2
printfn"%d"divRes2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
34
16
225
2
110
90
1000
10

Example2
//Module1
modulemodule1=
//Indentallprogramelementswithinmodulesthataredeclaredwithanequalsign.
letvalue1=100
letmodule1Functionx=
x+value1

//Module2
modulemodule2=
letvalue2=200
//Useaqualifiednametoaccessthefunction.
//frommodule1.
letmodule2Functionx=
x+(module1.module1Functionvalue2)
letresult=module1.module1Function25
printfn"%d"result
letresult2=module2.module2Function25
printfn"%d"result2

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput
125
325

F#NAMESPACES
Anamespaceisdesignedforprovidingawaytokeeponesetofnamesseparatefromanother.Theclass
namesdeclaredinonenamespacewillnotconflictwiththesameclassnamesdeclaredinanother.
AspertheMSDNlibrary,anamespaceletsyouorganizecodeintoareasofrelatedfunctionalityby
enablingyoutoattachanametoagroupingofprogramelements.

DeclaringaNamespace
Toorganizeyourcodeinanamespace,youmustdeclarethenamespaceasthefirstdeclarationinthe
file.Thecontentsoftheentirefilethenbecomepartofthenamespace.
namespace[parentnamespaces.]identifier

Thefollowingexampleillustratestheconcept

Example
namespacetesting
moduletestmodule1=
lettestFunctionxy=
printfn"ValuesfromModule1:%A%A"xy
moduletestmodule2=
lettestFunctionxy=
printfn"ValuesfromModule2:%A%A"xy
moduleusermodule=
do
testmodule1.testFunction("one","two","three")150
testmodule2.testFunction(seq{foriin1..10doyieldi*i})200

Whenyoucompileandexecutetheprogram,ityieldsthefollowingoutput

ValuesfromModule1:("one","two","three")150
ValuesfromModule2:seq[1;4;9;16;...]200

Potrebbero piacerti anche