F# 101
Upcoming SlideShare
Loading in...5
×
 

F# 101

on

  • 4,482 views

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

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

Statistics

Views

Total Views
4,482
Views on SlideShare
4,205
Embed Views
277

Actions

Likes
3
Downloads
64
Comments
0

5 Embeds 277

http://blog.cwa.me.uk 270
http://www.slideshare.net 4
http://feeds.feedburner.com 1
http://www.techgig.com 1
http://cache.baiducontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

F# 101 F# 101 Presentation Transcript

  • 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:somepath osearch”;; 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/