Professional Documents
Culture Documents
Introduction To F PDF
Introduction To F PDF
dmitrinesteruk @ gmail.com
http://spbalt.net
a programming paradigm that
treats computation as the evaluation
of mathematical functions and
avoids state and mutable data
Wikipedia
Higher-order functions
i => j => f(j)
Pure functions
Immutability
No side eects
(Tail) recursion
let f(x) = ; f(x-1);
Pattern matching
Math
Probabilistic models
Symbolic processing (parsing/lexing)
Symbolic dierentiation
Circuit verification
Multi-paradigm language in .NET stack
Functional
Imperative
Performance similar to C#
Interactive console
Support in Visual Studio
Debugger
Editor
Mono support
#light
printfnHello,F#!
#light
Light syntax cuts down on ceremony when
writing code
Indentation instead of begin/end
Use of in,done keywords not required
No semicolons
Currently mandatory will be default in future
printfnHello,F#
Writes a line to the console
A top-level binding (like a global function)
Part of FSharp.Core
Referenced implicitly
Appears in a generated _main()
Can Go To Definition
Can do it with a function
letsayHello=
printfnHello,F#!
sayHello
Or pass a parameter
letsayHellos=
printfns
sayHello"Hello,F#!"
Application operator |> (forward pipe)
letsayHellos=
s|>printfn//sameasprintfns
Explicit types
letlengtha=a.Length;//notok
letlength(a:string)=
a.Length//ok
Recursive definition
letrecfactorialn=
ifn<=1then1
elsen*factorial(n1)
Mutual recursion
letrecfuncAx=1+funcB(x)
andfuncBx=1funcA(x)
One statement per line, use in for more
letpowerOf4x=
lety=x*xiny*y
No implicit conversions
letGetXNamexname=
XName.op_Implicit(xname)
Aggressive strong typing
leto:obj=test;//fails
leto=boxtest;//ok
Mutability must be explicit
mutable keyword
variable<valueto assign
Clever switch statement
Can match values of any type
letmatchMex=
matchxwith
|1>printfn"one"
|2>printfn"two"
|_>printfn"somethingelse"
letsumAndProductab=
(a+b,a*b)
let(s,p)=sumAndProduct23
printfn"%d%d"sp
matchxwith
|Some(name)>printfnname
|None>printfnanonymous
Your typical CLR array
letpeople=[|
john;
jane;
jack
|]
people.Length
yields 3
Enumerable values
leta=seq[1;2;3]
letb=seq{foriin1..10>(i*i)}
Lazy-inited
seq{1..10000000}
Step
seq{1..2..10}
yields 1, 3, 5, 7, 9
Strings are char sequences
printfn"%d"(Seq.length"Hello")
Iterated with for .. in .. do
foriinmySeqdoprintfn%di
Linked list of values
[1;2;3]
letrecnonZeromyList=
matchmyListwith
|0::t>1::nonZerot
|h::t>h::nonZerot
|[]>[]
letrechtmlDecodetext=
matchtextwith
|&::g::t::;::tail>
>::htmlDecodetail//andsoon
A non-exhaustive match will throw a
MatchFailureException
shift(1,0)(100,100)
result is (101, 100)
letshiftRight=shift(1,0)
shiftRight(100,100)
result is (101, 100)
Keep a lookaside table of computed values
letrecfibn=
ifn<=2then1
elsefib(n1)+fib(n2)
Spawn one-by-one
forurlinurlsdo
Async.Spawn(download(url))
Expert F#
Don Syme et al.
F# for Scientists
Jon Harrop