F# 101 Liverpool Users of .NET - 15 th  May 2008 Chris Alcock  calcock@incanus.co.uk  http://blog.cwa.me.uk/
What is F# to me Interesting  Different A bit of fun
What is F#? Functional Programming Language Has history – similar to older languages from as early as the 1950's Based on OCAML
F# and the .NET Framework Created with the aim of proving that the CLR provided a basis for functional languages First Class Language in .NET Compiles down to CLR code Allows interop with .NET Assemblies
What is Functional Programming Most Programming Languages are Imperative C#, Java, Basic Programming in these languages has side effects Functional Programming is programming without side effects F# is not pure Functional as it also supports imperative programming
Getting Started with F# F# is a Microsoft Research project Latest version is 1.9.4.15 (at time of writing) Installer with VS2005/2008 integration (~18mb) available here: http://research.microsoft.com/fsharp/
Interactive Mode Very like Python, ruby, etc Great for testing simple things, and learning We will be using this for lots of the simple examples (DEMO)
Fsc.exe – The compiler Just like C#, VB.NET there is a Command Line Compiler But its much easier through Visual Studio (DEMO)
Hello World! Well, we need somewhere to start (DEMO) let str = “Hello World”;; sprintf “%s” str;;
Introducing Language Concepts
#light Light Weight Syntax mode Makes white space significant  Allows omission of begin end block keywords Allows omission of line terminator character(;) Makes code more readable and concise
let keyword Has two purposes  Defining variables Defining functions Variables let thisVar = 10 Functions let Add10 n = n+10
Type Inference F# uses type inference for all variables and function Sometime it needs a helping hand let (f:string) = “hello” Let Square (n:int) = n * n
Namespaces This is the equivalent of the c# using or VB imports Does not load assemblies, they must be referenced as usual (using #r in the console) #r “System.Windows.Forms.dll”;; #I “c:\some\path\to\search”;; to add reference path open NameSpace open System.IO
F# and .NET Libraries F# has its own library in the namespace  Microsoft.FSharp This contains special  types and functions  (eg. String.split) F# can also use the whole .NET framework Function Overloads are supported, you have to specify the types you are using to get the right function (DEMO)
Multi Line Functions Nothing much can be achieved with single line functions let sumThenSquare n m =    let sum = m + n in    sum * sum Calling Functions SumThenSquare 3 4;;
Local Functions Functions can define functions and use them let HelloPerson name =  let addHello n = "Hello " + n  let str = addHello name  sprintf "%s" str ;;
Recursion Functions in F# are not recursive by default Recursive functions must be marked with the  rec  keyword As with all languages its vital to ensure that recursive functions do actually complete (DEMO)
Function Composition and Pipelining This is where Functional Programming really looks like maths. fog x = g >> f  The operator is defined as let (>>) f g x = g(f(x)) Pipelining is all about calling functions and passing results to next function input |> function1 |> function2 (DEMO)
Pattern Matching Powerful construct Performs Decomposition Allows our code to make decisions Pattern Matching takes the form: match x with  | value -> what to do in this case  | othervalue where guardExpression-> action for this case (DEMOS)
Imutability Many language types are immutable Simplifies many things No longer have to worry about object identity Variable corruption in functions can't occur Thread safety be default Pure Functional Programming requires Immutability
Currying / Partial Function Application Named after Haskell Curry – a logician, who also has a programming language to his name Idea is to create a wrapper function which calls another function with partial parameters, with the remaining parameters being passed as arguments to the wrapper Demo should make it clearer (DEMO)
Tuples Tuples are a very simple yet useful data structure Often used as the return from functions let PairTuple = (val1, val2) Obtain Values: fst PairTuple  == val1 ,  snd PairTuple  = val2 fst and snd only apply to pairs Let a,b = PairTupple a = val1, b=a val2
Anonymous and Delegate Functions F# makes use of anonymous functions in a number of places Filtering Lists, Etc (fun x -> x *x) F# also allows functions to be passed into other functions as Parameters (DEMO)
Lists F# Lists are Immutable [] denotes a list (empty), and [1;2] is a populated list 1 :: [1;2;3] 'adds' element  1 before list and return a new list equivalent to [1;1;2;3]  [1;2] @ [3]  'adds' element 3 at the end of the list the new list Lots of other list functions (DEMO)
Types / Records F# is a typed language – however mostly handled by type inference.  Creating your own types is easy, and instancing them is simple type t =   { Field1 : type;   Field2 : type; } let f = {Field1 = 1; Field2 = 2} Objects can be cloned easily (DEMO)
Discriminated Unions Allows concrete types to be collected together Individual elements are called a discriminator Defined as follows: type DisUn =    | subtype1 of definition   | subtype 2 Very useful for modelling finite sealed set of choices
Sequences Sequences are actually System.Collections.Generic.IEnumerable<t> Sequences can be defined by range expressions seq{1..10} = seq [1,2,3,4,5,6,7,8,9,10] Like lists, sequences have helpers for common actions (append, map, filter, etc) Sequences can be Lazy initialized Sequences can be defined by functions (DEMO)
Objects F# is OO, so you can define your one objects This affords us Methods, Member varables and values, and encapsulation Defined as follows: type TheClass (Constructor Params) =    let privateVar = initVa;   member t.Field = valueToReturn   member t.Prop with get() = val and set(v) = expr (DEMO)
Benefits of Functional Programming Pure functional programming has lots of advantages No Side effects, so highly parallelizable Simple concise code Bugs are harder to introduce Powerful function support – currying and composition
Functional Enhancements to other languages Functional concepts are appearing in imperative languages now Lambda expressions First Class Functions Anonymous functions Bart De Smet has been looking at implementing pattern matching in C# http://community.bartdesmet.net/blogs/bart/
Imperative Programming F# is not pure functional, it allows imperative programming too! This Section: Mutable, references  flow control,  arrays  .NET collections
Mutability <- operator allows assigning of values let f = 1 f <- 2  (ERROR!) Can't alter value f by default F# Supports mutable data via the mutable keyword let mutable f = 1 f <- 3  (all fine this time)
References Reference variables are defined by the ref keyword let f = ref 0 Reference assignment can be made with the operator := let f := 2 Values can be obtained with the ! Operator: let b = !f
Flow Control (looping and iterating) F# supports common flow control statements For for var = start to end do expr done While while expr do expr done Sequence Loops for pattern in expression do expr done (DEMO)
Mutable Arrays Arrays are defined using [| values |] Arrays allocate memory immediatly Like lists and sequences F# provides helper functions Individual elements can be accessed and modified Arrays can be split into sub arrays (DEMO)
.NET Collections F# allows us to use .NET collections This allows us to use  System.Collections.Generic.List<t> Dictionaries, Queues, etc F# aliases System.Collections.List<g> as ResizeArray<g>  (DEMO)
Functional Programming with Side Effects Mutable loops can often be replaced with recursion Try to separate the computation from the Side effect code Separate Mutable Data structure - Keep mutable data internal to methods to prevent tampering Consider the scale of your side effects
F# in real use - WinForms (DEMO)
Sources of Further Information Expert F# Don Syme HubFS http://cs.hubfs.net/ Adventures in F# Matthew Podwysocki http://weblogs.asp.net/podwysocki/

F# 101

  • 1.
    F# 101 LiverpoolUsers of .NET - 15 th May 2008 Chris Alcock calcock@incanus.co.uk http://blog.cwa.me.uk/
  • 2.
    What is F#to me Interesting Different A bit of fun
  • 3.
    What is F#?Functional Programming Language Has history – similar to older languages from as early as the 1950's Based on OCAML
  • 4.
    F# and the.NET Framework Created with the aim of proving that the CLR provided a basis for functional languages First Class Language in .NET Compiles down to CLR code Allows interop with .NET Assemblies
  • 5.
    What is FunctionalProgramming Most Programming Languages are Imperative C#, Java, Basic Programming in these languages has side effects Functional Programming is programming without side effects F# is not pure Functional as it also supports imperative programming
  • 6.
    Getting Started withF# F# is a Microsoft Research project Latest version is 1.9.4.15 (at time of writing) Installer with VS2005/2008 integration (~18mb) available here: http://research.microsoft.com/fsharp/
  • 7.
    Interactive Mode Verylike Python, ruby, etc Great for testing simple things, and learning We will be using this for lots of the simple examples (DEMO)
  • 8.
    Fsc.exe – Thecompiler Just like C#, VB.NET there is a Command Line Compiler But its much easier through Visual Studio (DEMO)
  • 9.
    Hello World! Well,we need somewhere to start (DEMO) let str = “Hello World”;; sprintf “%s” str;;
  • 10.
  • 11.
    #light Light WeightSyntax mode Makes white space significant Allows omission of begin end block keywords Allows omission of line terminator character(;) Makes code more readable and concise
  • 12.
    let keyword Hastwo purposes Defining variables Defining functions Variables let thisVar = 10 Functions let Add10 n = n+10
  • 13.
    Type Inference F#uses type inference for all variables and function Sometime it needs a helping hand let (f:string) = “hello” Let Square (n:int) = n * n
  • 14.
    Namespaces This isthe equivalent of the c# using or VB imports Does not load assemblies, they must be referenced as usual (using #r in the console) #r “System.Windows.Forms.dll”;; #I “c:\some\path\to\search”;; to add reference path open NameSpace open System.IO
  • 15.
    F# and .NETLibraries F# has its own library in the namespace Microsoft.FSharp This contains special types and functions (eg. String.split) F# can also use the whole .NET framework Function Overloads are supported, you have to specify the types you are using to get the right function (DEMO)
  • 16.
    Multi Line FunctionsNothing much can be achieved with single line functions let sumThenSquare n m = let sum = m + n in sum * sum Calling Functions SumThenSquare 3 4;;
  • 17.
    Local Functions Functionscan define functions and use them let HelloPerson name = let addHello n = &quot;Hello &quot; + n let str = addHello name sprintf &quot;%s&quot; str ;;
  • 18.
    Recursion Functions inF# are not recursive by default Recursive functions must be marked with the rec keyword As with all languages its vital to ensure that recursive functions do actually complete (DEMO)
  • 19.
    Function Composition andPipelining This is where Functional Programming really looks like maths. fog x = g >> f The operator is defined as let (>>) f g x = g(f(x)) Pipelining is all about calling functions and passing results to next function input |> function1 |> function2 (DEMO)
  • 20.
    Pattern Matching Powerfulconstruct Performs Decomposition Allows our code to make decisions Pattern Matching takes the form: match x with | value -> what to do in this case | othervalue where guardExpression-> action for this case (DEMOS)
  • 21.
    Imutability Many languagetypes are immutable Simplifies many things No longer have to worry about object identity Variable corruption in functions can't occur Thread safety be default Pure Functional Programming requires Immutability
  • 22.
    Currying / PartialFunction Application Named after Haskell Curry – a logician, who also has a programming language to his name Idea is to create a wrapper function which calls another function with partial parameters, with the remaining parameters being passed as arguments to the wrapper Demo should make it clearer (DEMO)
  • 23.
    Tuples Tuples area very simple yet useful data structure Often used as the return from functions let PairTuple = (val1, val2) Obtain Values: fst PairTuple == val1 , snd PairTuple = val2 fst and snd only apply to pairs Let a,b = PairTupple a = val1, b=a val2
  • 24.
    Anonymous and DelegateFunctions F# makes use of anonymous functions in a number of places Filtering Lists, Etc (fun x -> x *x) F# also allows functions to be passed into other functions as Parameters (DEMO)
  • 25.
    Lists F# Listsare Immutable [] denotes a list (empty), and [1;2] is a populated list 1 :: [1;2;3] 'adds' element 1 before list and return a new list equivalent to [1;1;2;3] [1;2] @ [3] 'adds' element 3 at the end of the list the new list Lots of other list functions (DEMO)
  • 26.
    Types / RecordsF# is a typed language – however mostly handled by type inference. Creating your own types is easy, and instancing them is simple type t = { Field1 : type; Field2 : type; } let f = {Field1 = 1; Field2 = 2} Objects can be cloned easily (DEMO)
  • 27.
    Discriminated Unions Allowsconcrete types to be collected together Individual elements are called a discriminator Defined as follows: type DisUn = | subtype1 of definition | subtype 2 Very useful for modelling finite sealed set of choices
  • 28.
    Sequences Sequences areactually System.Collections.Generic.IEnumerable<t> Sequences can be defined by range expressions seq{1..10} = seq [1,2,3,4,5,6,7,8,9,10] Like lists, sequences have helpers for common actions (append, map, filter, etc) Sequences can be Lazy initialized Sequences can be defined by functions (DEMO)
  • 29.
    Objects F# isOO, so you can define your one objects This affords us Methods, Member varables and values, and encapsulation Defined as follows: type TheClass (Constructor Params) = let privateVar = initVa; member t.Field = valueToReturn member t.Prop with get() = val and set(v) = expr (DEMO)
  • 30.
    Benefits of FunctionalProgramming Pure functional programming has lots of advantages No Side effects, so highly parallelizable Simple concise code Bugs are harder to introduce Powerful function support – currying and composition
  • 31.
    Functional Enhancements toother languages Functional concepts are appearing in imperative languages now Lambda expressions First Class Functions Anonymous functions Bart De Smet has been looking at implementing pattern matching in C# http://community.bartdesmet.net/blogs/bart/
  • 32.
    Imperative Programming F#is not pure functional, it allows imperative programming too! This Section: Mutable, references flow control, arrays .NET collections
  • 33.
    Mutability <- operatorallows assigning of values let f = 1 f <- 2 (ERROR!) Can't alter value f by default F# Supports mutable data via the mutable keyword let mutable f = 1 f <- 3 (all fine this time)
  • 34.
    References Reference variablesare defined by the ref keyword let f = ref 0 Reference assignment can be made with the operator := let f := 2 Values can be obtained with the ! Operator: let b = !f
  • 35.
    Flow Control (loopingand iterating) F# supports common flow control statements For for var = start to end do expr done While while expr do expr done Sequence Loops for pattern in expression do expr done (DEMO)
  • 36.
    Mutable Arrays Arraysare defined using [| values |] Arrays allocate memory immediatly Like lists and sequences F# provides helper functions Individual elements can be accessed and modified Arrays can be split into sub arrays (DEMO)
  • 37.
    .NET Collections F#allows us to use .NET collections This allows us to use System.Collections.Generic.List<t> Dictionaries, Queues, etc F# aliases System.Collections.List<g> as ResizeArray<g> (DEMO)
  • 38.
    Functional Programming withSide Effects Mutable loops can often be replaced with recursion Try to separate the computation from the Side effect code Separate Mutable Data structure - Keep mutable data internal to methods to prevent tampering Consider the scale of your side effects
  • 39.
    F# in realuse - WinForms (DEMO)
  • 40.
    Sources of FurtherInformation Expert F# Don Syme HubFS http://cs.hubfs.net/ Adventures in F# Matthew Podwysocki http://weblogs.asp.net/podwysocki/