Fsharp Slides

download Fsharp Slides

of 15

Transcript of Fsharp Slides

  • 8/10/2019 Fsharp Slides

    1/15

    1

    www.itu.dk 1

    Programming language seminar 2011

    The F# language

    Peter SestoftWednesday 2011-08-31

    www.itu.dk 2

    Course plan

    Four cycles, each containing a mini-project: F#

    Types and type inference

    Scala and Scala actors

    Programming language technology inside a high-performance spreadsheet implementation, more F#

    Final course report, individual, 10 pages

    Either continuation of a mini-project Or some other topic/language/... that you find

    interesting and want to explore

    Wednesdays (0900-1200) lectures or consultations, see homepage

    Homepagehttp://www.itu.dk/courses/SPLG/E2011/

  • 8/10/2019 Fsharp Slides

    2/15

    2

    www.itu.dk 3

    Sources Hansen+Rischel: Functional programming with F#

    (DTU, draft 2011) PDF distributed onlyto this course; do not redistribute

    Sestoft: Programming Language Concepts forSoftware Developers (PLCSD), ITU August 2011

    Complete PDF on course homepage

    Materials on Scala and Scala actors

    Sestoft: Spreadsheet technology(ITU, later 2011)

    Homepage http://www.itu.dk/courses/SPLG/E2011/ Schedule

    Reading materials

    Exercises

    Occasional example programs from lectures

    Why F# and Scala

  • 8/10/2019 Fsharp Slides

    3/15

    3

    www.itu.dk

    F# Developed by Don Syme at Microsoft

    Research, Cambridge UK

    A functional language in the ML family

    With many additions and innovations

    Dimension types

    Object-oriented features

    Workflows (asynchronous computing)

    Runs on the .NET platform (like C#, VB.NET)

    For Windows, Linux and MacOS

    Included in Visual Studio 2010

    Or from http://msdn.microsoft.com/en-us/fsharpand use Mono 2.10 or .NET redistributable

    5

    F# values, declarations and types

    Interactive system top-level fsi

    Strongly typed, types are inferred

    Immutability: letis bindingnot assignment

    let res = 3+4;;

    let y = sqrt 2.0;;

    let large = 10 < res;;

    y > 0.0 && 1.0/y > 7.0;;

    if 3 < 4 then 117 else 118;;

    let rektor = "Mads " + "Tofte";;

    Expression

    Declaration

  • 8/10/2019 Fsharp Slides

    4/15

    4

    www.itu.dk 7

    F# function definitions

    A function that finds the average of twofloating-point numbers?

    let circleArea r = System.Math.PI * r * r;;

    let mul2 x = 2.0 * x;;

    Functionname

    Parameter

    > circleArea 10.0;;val it : float = 314.1592654

    www.itu.dk 8

    F# recursive function definitions

    Same in Java/C#/C/C++:

    let rec fac (n : int) : int =if n=0 then 1else n * fac(n-1);;

    int fac(int n) {if (n==0)return 1;

    elsereturn n * fac(n-1);

    }

  • 8/10/2019 Fsharp Slides

    5/15

    5

    www.itu.dk 9

    F# type constraints

    What if we give a wrong type constraint?

    let isLarge (x : float) : bool = 10.0 < x;;val isLarge : float -> bool

    let isLarge x = 10 < x;;val isLarge : int -> bool

    www.itu.dk 10

    F# pattern matching

    A pattern can be a variable a constant

    a wildcard (_)

    a constructor application x :: xr

    a list []or [x]or x::y::xr

    a tuple (x, y)or (2, 29)or ([], x::xr)

    let rec fac n =match n with

    | 0 -> 1| _ -> n * fac(n-1);;

  • 8/10/2019 Fsharp Slides

    6/15

    6

    www.itu.dk 11

    F# pairs and tupleslet p = (2, 3);;let w = (2, true, 3.4, "blah");;

    let add (x, y) = x + y;;

    let noon = (12, 0);;let talk = (15, 15);;

    let earlier ((h1, m1), (h2, m2)) =h1

  • 8/10/2019 Fsharp Slides

    7/15

    7

    www.itu.dk 13

    List append (@)

    F# data (lists, pairs, ) are immutable

    This makes list sharing unobservable

    let x1 = [7; 9; 13];;let x3 = [47; 11];;

    let x1x3 = x1 @ x3;;

    Result is[7; 9; 13; 47; 11]

    9

    11

    13

    47

    7

    9 137

    x1

    x3

    x1x3

    www.itu.dk 14

    F# defining functions on lists

    How compute the length of a list? How compute the average of a list?

    let rec sum xs =match xs with

    | [] -> 0| x::xr -> x + sum xr;;

  • 8/10/2019 Fsharp Slides

    8/15

    8

    www.itu.dk 15

    F# record types and records

    A record type for course information: title,teacher, semester?

    type phonerec ={ name : string; phone : int };;

    let x ={ name = "Kasper"; phone = 5170 };;

    x.name;;x.phone;;

    www.itu.dk 16

    F# exceptions: raise and catch

    exception IllegalHour;;let mins h =

    if h < 0 || h > 23 then raise IllegalHourelse h * 60;;

    try (mins 25)with IllegalHour -> -1;;

  • 8/10/2019 Fsharp Slides

    9/15

    9

    www.itu.dk 17

    failwith raises the Failure exceptionlet mins h =

    if h < 0 || h > 23 then failwith "Illegal hour"else h * 60;;

    let mins h =if h < 0 || h > 23 then

    failwithf "Illegal hour, h=%d" helse

    h * 60;;

    mins 25;;[...] FailureException: Illegal hour, h=25

    Formattedfailwith

    Like Cprintf

    www.itu.dk 18

    F# algebraic datatypes

    Algebraic datatype, discriminated union

    A person is either a teacher or a student:

    type person =| Student of string| Teacher of string * int;;

    let people = [Student "Niels"; Teacher("Peter", 5083)];;

    let getphone person =match person with

    | Teacher(name, phone) -> phone| Student name -> failwith "no phone";;

    A type to represent weekdays?

    How would you do person/Student/Teacher in Java/C#?

  • 8/10/2019 Fsharp Slides

    10/15

    10

    www.itu.dk 19

    F# curried functions

    Function application is left associative:

    addc x y means

    (addc x) y The function type arrow is right associative:

    int -> int -> int means int -> (int -> int)

    What would (int -> int) -> int mean?

    let addp (x, y) = x + y;;let res1 = addp(17, 25);;

    let addc x y = x + y;;let res2 = addc 17 25;;

    Type?

    Type?

    www.itu.dk 20

    Anonymous functions in F#

    A higher-order function takes anotherfunction as argument

    let rec map f xs =match xs with

    | [] -> []| x::xr -> f x :: map f xr

    (a->b) -> (a list -> b list)

    let mul2 x = 2.0 * x;;map mul2 [4.0; 5.0; 89.0];; [8.0; 10.0; 178.0]

    Anonymous functionsmap (fun x -> 2.0 * x) [4.0; 5.0; 89.0]

    map (fun x -> x > 10.0) [4.0; 5.0; 89.0]

    [8.0; 10.0; 178.0]

    [false; false; true]

  • 8/10/2019 Fsharp Slides

    11/15

    11

    21

    delegate R Func()delegate R Func(A1 x1)delegate R Func(A1 x1, A2 x2)

    Higher-order functions in C# C# delegate (function) types

    Anonymous function/method expressions

    (int x) => x>10x => x>10x => x*x

    C# 3.0

    fun (x:int) -> x>10fun x -> x>10fun x -> x*x

    F#

    unit -> intbool -> intint * bool -> string

    FuncFuncFunc

    C# 3.0F#

    www.itu.dk 22

    F# polymorphic functions

    Same as a generic method in Java or C#

    let rec len xs =match xs with

    | [] -> 0| x::xr -> 1 + len xr;;

    val len : 'a list -> int

    The functiondoesnt look at

    the list elements

    so the functionis polymorphic

    static int Count(IEnumerable xs) { ... }

    len [7; 9; 13]len [true; true; false; true]len ["foo"; "bar"]len [("Peter", 47)]

    and works in

    any type of list

  • 8/10/2019 Fsharp Slides

    12/15

    12

    www.itu.dk 23

    F# polymorphic types

    Same as a generic type in Java or C#:

    type 'a tree =| Lf| Br of 'a * 'a tree * 'a tree

    Br(42, Lf, Lf)Br("quoi?", Lf, Lf)Br(("Peter", 47), Lf, Lf)

    The datatype hassame structure

    regardless of nodevalue type

    What typeinstances here?

    class ArrayList { ... }interface IEnumerable { ... }struct Pair { ... }delegate R Func(A x);

    www.itu.dk 24

    Polymorphic functionson polymorphic types

    Return the trees node values in pre-order

    first root, then left subtree, then right subtree

    Works on any type of tree

    What is the type of this function?

    let rec preorder1 t =match t with| Lf -> []| Br(v, t1, t2) -> v :: preorder1 t1 @ preorder1 t2

  • 8/10/2019 Fsharp Slides

    13/15

    13

    www.itu.dk

    Accumulating parameters The append (@) operation may be slow

    A faster version of preorder, no append!

    let rec preo t acc =match t with| Lf -> acc| Br(v, t1, t2) -> v :: preo t1 (preo t2 acc);;

    let preorder2 t = preo t [];;

    This works becausepreo t acc = preorder1 t @ acc

    Sopreorder2 t = preo t [] = preorder1 t

    Accumulatingparameter

    O(n) versus O(n2)

    Can be 1000 x faster

    Try #time;;in F#

    www.itu.dk

    Uniform iteration over a list

    Generalizing 0/1 to e, and +/* to f:

    let rec sum xs =match xs with

    | [] -> 0| x::xr -> x + sum xr

    let rec prod xs =match xs with

    | [] -> 1| x::xr -> x * prod xr

    let rec foldr f xs e =match xs with

    | [] -> e| x::xr -> f x (foldr f xr e)

    The foldr function replaces :: by f, and [] by e:foldr !(x1::x2::::xn::[]) e = x1!(x2!(... !(xn!e) ))

    ('a -> 'b -> 'b) ->'a list -> 'b -> 'b

    int list -> int

    List.foldBack in F#

  • 8/10/2019 Fsharp Slides

    14/15

    14

    www.itu.dk 27

    Many functions definable using foldrlen xs = foldr (fun _ res -> 1+res) xs 0

    sum xs = foldr (fun x res -> x+res) xs 0

    prod xs = foldr (fun x res -> x*res) xs 1

    map g xs = foldr (fun x res -> g x :: res) xs []

    listconcat xss = foldr (fun xs res -> xs @ res) xss []

    strconcat ss = foldr (fun s res -> s ^ res) ss "

    filter p xs = list of those x in xs for which p x is true

    forall p xs = p x is true for all x in xs

    exists p xs = p x is true for some x in xs

    www.itu.dk 28

    Composing functions, pipe

    Given list xs, throw away small numbers, square theremaining numbers, and compute their sum:

    sum (map (fun x -> x*x) (filter (fun x -> x>10) xs))

    x |> f = f x

    Somewhat difficult to read: inside-out

    Idea: Define infix higher-order function |>

    Now the list operations combine naturally:

    xs |> filter (fun x -> x>10) |> map (fun x -> x*x) |> sum

  • 8/10/2019 Fsharp Slides

    15/15

    15

    www.itu.dk

    F# mutable references A reference is a cell that can be updated

    let r = ref 177!r(r := !r+1; !r)!r

    Useful for generation of new names etc:

    let nextlab = ref -1;;let newLabel () = (nextlab := 1 + !nextlab;

    "L" + string (!nextlab));;newLabel();;newLabel();;newLabel();;

    Create int reference

    Assign to reference

    Dereference

    www.itu.dk

    Reading and exercises

    Install F# and experiment with it

    Either Visual Studio 2010 (a monster, availablevia your MSDNAA account)

    Or using Mono from www.mono-project.com

    Read Hansen & Rischel

    Chapters 1 to 5

    There are exercises in Hansen & Rischel

    Do them as needed

    Or do the first steps of miniproject 1

    30