lettotalArray()=// define an array literal
letarray=[|1;2;3|]// define a counter
lettotal=ref0// loop over the array
forxinarraydo// keep a running total
total:=!total+x// print the total
printfn"total: %i"!totaltotalArray()
Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// define an array literal
letrhymeArray=[|"Went to market";"Stayed home";"Had roast beef";"Had none"|]// unpack the array into identifiers
letfirstPiggy=rhymeArray.[0]letsecondPiggy=rhymeArray.[1]letthirdPiggy=rhymeArray.[2]letfourthPiggy=rhymeArray.[3]// update elements of the array
rhymeArray.[0]<-"Wee,"rhymeArray.[1]<-"wee,"rhymeArray.[2]<-"wee,"rhymeArray.[3]<-"all the way home"
1
2
3
4
5
6
7
8
9
10
// 交错数组
// define a jagged array literal
letjagged=[|[|"one"|];[|"two";"three"|]|]// unpack elements from the arrays
letsingleDim=jagged.[0]letitemOne=singleDim.[0]letitemTwo=jagged.[1].[0]// print some of the unpacked elements
printfn"%s %s"itemOneitemTwo
// 数组初始化
// an array of characters
letchars=[|'1'..'9'|]// an array of tuples of number, square
letsquares=[|forxin1..9->x,x*x|]// print out both arrays
printfn"%A"charsprintfn"%A"squares// 数组切片
// 切片语法也可用于List
letarr=[|1;3;5;7;11;13|]letmiddle=arr.[1..4]// [|3; 5; 7; 11|]
letstart=arr.[..3]// [|1; 3; 5; 7|]
lettail=arr.[1..]// [|3; 5; 7; 11; 13|]
letocean=Array2D.create1001000// Create a ship:
foriin3..6doocean.[i,5]<-1// Pull out an area hit by a 'shell':
lethitArea=ocean.[2..5,2..5]// We can see a rectangular area by 'radar':
letradarArea=ocean.[3..4,*]
ifx=1thenprintfn"eq"elseprintfn"ne"// an array for words
letwords=[|"Red";"Lorry";"Yellow";"Lorry"|]// use a for loop to print each element
forwordinwordsdoprintfn"%s"wordforindex=0toArray.lengthwords-1doprintfn"%s"words.[index]forindex=Array.lengthwordsdownto0doprintfn"%s"words.[index]letmutabletem=10while(tem>0)dotem<-tem-1// Count upwards:
foriin0..10doprintfn"%i green bottles"i// Count downwards:
foriin10..-1..0doprintfn"%i green bottles"i// Count upwards in tens
foriin0..10..100doprintfn"%i green bottles"i
Calling Static Methods and Properties from .NET Libraries
// calling static method
ClassName.MethodName(arg1,arg2,arg3)// or in a curried way
letmethodNamearg1arg2arg3=ClassName.MethodName(arg1,arg2,arg3)lettemMethodarg1=methodNamearg1// named paramaters
openSystem.IO// open a file using named arguments
letfile=File.Open(path="test.txt",mode=FileMode.Append,access=FileAccess.Write,share=FileShare.None)// close it!
file.Close()
Using Objects and Instance Members from .NET Libraries
1
2
3
4
5
6
7
8
9
10
openSystem.IO// file name to test
letfilename="test.txt"// bind file to an option type, depending on whether
// the file exist or not
letfile=ifFile.Exists(filename)thenSome(newFileInfo(filename,Attributes=FileAttributes.ReadOnly))elseNone
1
2
3
4
5
6
7
8
9
openSystem// how to wrap a method that take a delegate with an F# function
// the <_> means don't care the type of the Predicate's argument
letfindIndexfarr=Array.FindIndex(arr,newPredicate<_>(f))// define an array literal
letrhyme=[|"The";"cat";"sat";"on";"the";"mat"|]// print index of the first word ending in 'at'
printfn"First word ending in 'at' in the array: %i"(rhyme|>findIndex(funw->w.EndsWith("at")))
Using Indexers from .NET Libraries
1
2
3
4
5
6
7
8
9
10
11
openSystem.Collections.Generic// create a ResizeArray
letstringList=lettemp=newResizeArray<string>()temp.AddRange([|"one";"two";"three"|]);temp// unpack items from the resize array
letitemOne=stringList.Item(0)letitemTwo=stringList.[1]// print the unpacked items
printfn"%s %s"itemOneitemTwo
openSystem.TimerslettimedMessages()=// define the timer
lettimer=newTimer(Interval=3000.0,Enabled=true)// a counter to hold the current message
letmutablemessageNo=0// the messages to be shown
letmessages=["bet";"this";"gets";"really";"annoying";"very";"quickly"]// add an event to the timer
timer.Elapsed.Add(fun_->// print a message
printfn"%s"messages.[messageNo]messageNo<-messageNo+1ifmessageNo=messages.Lengththentimer.Enabled<-false)timedMessages()
openSystem.TimerslettimedMessagesViaDelegate()=// define the timer
lettimer=newTimer(Interval=3000.0,Enabled=true)// a counter to hold the current message number
letmutablemessageNo=0// the messages to be shown
letmessages=["bet";"this";"gets";"really";"annoying";"very";"quickly"]// function to print a message
letprintMessage=fun__->// print a message
printfn"%s"messages.[messageNo]messageNo<-(messageNo+1)%messages.Length// wrap the function in a delegate
letdel=newElapsedEventHandler(printMessage)// add the delegate to the timer
timer.Elapsed.AddHandler(del)|>ignore// return the time and the delegate so we can
// remove one from the other later
(timer,del)// Run this first:
lettimer,del=timedMessagesViaDelegate()// Run this later:
timer.Elapsed.RemoveHandler(del)
Pattern Matching with .NET Types
1
2
3
4
5
6
7
8
9
10
11
12
13
// a list of objects
letsimpleList=[box1;box2.0;box"three"]// a function that pattern matches over the
// type of the object it is passed
letrecognizeType(item:obj)=matchitemwith|:?System.Int32->printfn"An integer"|:?System.Double->printfn"A double"|:?System.String->printfn"A string"|_->printfn"Unknown type"// iterate over the list of objects
List.iterrecognizeTypesimpleList
1
2
3
4
5
6
7
8
9
10
11
12
// list of objects
letanotherList=[box"one";box2;box3.0]// pattern match and print value
letrecognizeAndPrintType(item:obj)=matchitemwith|:?System.Int32asx->printfn"An integer: %i"x|:?System.Doubleasx->printfn"A double: %f"x|:?System.Stringasx->printfn"A string: %s"x|x->printfn"An object: %A"x// iterate over the list pattern matching each item
List.iterrecognizeAndPrintTypeanotherList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
try// look at current time and raise an exception
// based on whether the second is a multiple of 3
ifSystem.DateTime.Now.Second%3=0thenraise(newSystem.Exception())elseraise(newSystem.ApplicationException())with|:?System.ApplicationException->// this will handle "ApplicationException" case
printfn"A second that was not a multiple of 3"|_->// this will handle all other exceptions
printfn"A second that was a multiple of 3"
The |> Operator
1
2
// the definition of |>
let(|>)xf=fx
1
2
3
4
5
6
7
8
9
10
11
// grab a list of all methods in memory
letmethods=System.AppDomain.CurrentDomain.GetAssemblies()|>List.ofArray|>List.map(funassm->assm.GetTypes())|>Array.concat|>List.ofArray|>List.map(funt->t.GetMethods())|>Array.concat// print the list
printfn"%A"methods