1 / 56

Let the |> fun begin

An introduction to F#. Let the |> fun begin. Bogdan Brinzarea-Iamandi Banca Romaneasca. 22 February 2010. Agenda. History. “The most original new face in computer languages since Bjarne Stroustrup developed C++ in the early 1980‘s”

mariah
Download Presentation

Let the |> fun begin

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. An introduction to F# Let the |> fun begin Bogdan Brinzarea-Iamandi BancaRomaneasca 22 February 2010

  2. Agenda

  3. History

  4. “The most original new face in computer languages since BjarneStroustrup developed C++ in the early 1980‘s” http://www.simple-talk.com/opinion/geek-of-the-week/don-syme-geek-of-the-week/ F is for fun

  5. What is F#? • Functional Programming Language • Will ship with Visual Studio 2010 • Deep roots in OCaml (http://caml.inria.fr) • Developed by Microsoft Research http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/

  6. Why should F# matter to me? • Succinctness • Type safety • Type inference • Expressivity • Scripting • Performance • Seamless integration with .NET

  7. Why should F# matter to me? • Functional programming • Imperative programming • Object oriented programming • Scripted programming

  8. Why should F# matter to me? • Well suited for: • Technical programming • Algorithmic programming • Parallel programming • Asynchronous programming • Explorative programming • Financial computing

  9. From imperative to functional programming

  10. Fibonacci C# static IEnumerable<int> Fibonacci { get{ inti = 1; int j = 2; while (true) { int n = i; yield return n; i = j; j = j + n; } } }

  11. Fibonacci F# let fibs = Seq.unfold (fun (i,j) -> Some(i,(j,i+j))) (1,2)

  12. Functional programming • Much more like our mind thinks • Easy to grasp for scientists • Pure functional programming has no side effects - immutability • Highly parallelizable • Powerful function support with currying and composition

  13. Functional features in other languages • C# 3.0 already has lambda expressions, anonymous functions, first class functions, anonymous types • Matthew Podwysocki - Functional C# http://code.msdn.microsoft.com/FunctionalCSharp/ • Bart de Smet http://bartdesmet.net/blogs/bart/ • Luca Bolognese http://blogs.msdn.com/lucabol/

  14. Imperative programming • Variable and assignment as main operations • In C# value types are immutable • F# is not pure functional as it has • Flow control (for, while, if) • Mutable keyword • Reference cells • Arrays

  15. Imperative vs Functional MSDN Library http://msdn.microsoft.com/en-us/library/bb669144.aspx

  16. Fundamentals

  17. #light • Lightweight syntax • Makes whitespaces significant • Lets you leave out tokens such as begin end ; ;; in • Makes code more readable and concise

  18. Hello world! printfn"Hello world!"

  19. Let keyword // define a value let message ="Hello world!“ // define a function value let sqr x = x*x • Binds forever a value or function value to an identifier • DOES NOT assign a value to an identifier • The identifiers are immutable • The compiler infers the types

  20. Type inference • F# is statically typed • The compiler infers the type for all variables and functions • We need to specify only when it cannot be deduced • Every value and expression has a definite type at compile time

  21. Type inference • Automatic generalization - if the type is not specified it is inferred as generic // 'a -> 'b -> 'a * 'b let pair x y = (x , y)

  22. Type inference • The return type of a function is determined by the type of the last expression in the function. // int->int->int letadd1 x y = x + y +1 // float->float->float letadd10 x y = x + y + 1.0

  23. Type inference • We can give the compiler a little help // help inferring the type let (message:string) = "Hello world!" let add (x:float) (y:float) = x+y let sum = add 2.0 1.0

  24. Fun or lambda expressions • Can be used as parameters to other functions let squares = Array.map (fun x->x*x)[|0..10|]

  25. Recursive functions • Functions are not recursive by default • Make sure the recursively function ends • Use the rec keyword together with let let recFibonacci n = if n<2then n else Fibonacci n-1 + Fibonacci n-2

  26. Currying or partial functions • Named after Haskell Curry • A function that calls another function and returns a function or • A partial function letadd x y = x + y let add5 = add 5 let result = add5 6

  27. Local identifiers • Indentation matters let SquareAndSum x y = let sqr x = x * x sqr x + sqr y

  28. Basic operators

  29. Basic types

  30. Pipelines and functions composition • Scientists love it • Composition f(g(x)) g >> f • Pipelines take an input of a function and pass it to the next one input |> function 1 |> function 2

  31. Data types

  32. Tuples • A group of unnamed but ordered values • Can contain different types • In .NET System.Tuple

  33. Arrays • All elements of the array must have the same type • Elements are mutable • A lot of helper functions to choose from (map, filter, iter etc.) let array1 = [|0; 1; 2 |] let array2 = [|0..10 |] let array3 = [| for i in 0..10 -> i|]

  34. Lists • A series of elements all of same (base) type • Lists are immutable • :: (cons operator) adds an element to the head of the list • @concatenates lists • Head, Tail properties • A lot of helper functions to choose from (head, tail, nth, map, iter, filter) let list1 = [ 1;2;3]

  35. Sequences • A series of elements all of same type • Equivalent to System.Collections.Generic.IEnumerable • Sequence expressions evaluate to sequences • A lot of helper functions to choose from (map, filter, iter) same as for lists let seq1 =seq {1..10}

  36. Discriminated unions • A way of grouping different values and types • Used to represent tree structures • Data is not fixed • Each possible option has a case identifier type Tree = | Nil | Node of int * Tree * Tree

  37. Options • An option wraps a value indicating whether it exists or not • They are a simple example of discriminated union // a: int option let a = Some (42) // b: 'a option let b = None

  38. Records • Simple way of grouping named values • We can use record expressions to set values • Easy cloning with copy and update record expressions

  39. Pattern matching

  40. Pattern matching at a glance • Offers branching of the control based on comparison of an expression with a set of patterns • One of the most powerful features of F# • Not a simple switch statement • Haskell, ML and OCaml also have it

  41. match expressions • When guards to add extra condition to the pattern // Match expression match test-expression with | pattern1 [ whencondition ] -> result-expression1 | pattern2 [ whencondition ] -> result-expression2 | ...

  42. Patterns

  43. Patterns

  44. Pattern matching letrec f = function | x when x < 0 ->failwith"Negative values are not allowed." | 0 | 1 as x -> x | x -> f (x-1) + f (x-2)

  45. Active patterns • Pattern matching of Algebraic Data Types (ADTs) • Allow to define named partitions for input data • Partial active patterns when we need to partition only part of the input • Parameterized active patterns when we have more than one argument

  46. Mutability vs immutability

  47. Mutability • Use mutable to make a variable mutable let mutable a =1 a <- 2 • Arrays are mutable let array = [|1..10|] array.[2]<- 5

  48. Reference cells • ref operator allows to box mutable values inside reference cells type Ref<'a> = { mutable contents: 'a } • byref keyword to ask for a reference cell or the address of a typical variable

  49. Object Oriented Programming

  50. Classes type[access-modifier] type-name [type-params]( parameter-list ) [ as identifier ] = [ class ] [inherit base-type-name(base-constructor-args) ] [ let-bindings ] [ do-bindings ] member-list • Let bindings define fields or function values local to the class • Do bindings define code to be executed upon creation • Identifier gives a name to the instance variable

More Related