F# 101


Published on

F# Language Introduction - Liverpool Users of .NET 15th May 2008

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • F# 101

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