intro f# functional_programming

82
F# Functional Programming

Upload: mauro-ghiani

Post on 26-Jul-2015

28 views

Category:

Software


0 download

TRANSCRIPT

F#Functional Programming

F#

F# is a multiparadigmprogramming language

built on .NET

F#F# is a scalable, simple, succinct, type-safe, type-inferred, practical, efficiently

executing functional-first/imperative/object –

oriented, explorative Open Source programming language built

on .NET

F# and Open Source

F# 4.0 compiler + library

Open Source

Apache 2.0 license

F# is case-sensitive

let number = 1 let Number = 2 let NUMBER = 3

Whitespace/Indentation/Scope The F# compiler allows you to use whitespace to delimit code blocks.

let sum (x,y) = x + y

Declarations

let pi = 3.14159 floating-point constant

let sum x y = x + y a function in two arguments

Let let [value,

function, module, namespace,

class] = expression

Types of Defined EntitiesF# manages to find types automatically:This is called type inferenceFor instance

let pi = 3.14159Here, pi will automatically obtain the type float since 3.14159 can only have type float

Explicit Type Declarationslet sum x y = x + y

F# will assume that “+” is plus on the type int.

let sum x y = (x + y) : floatIt forces the function to have type float

.NET Interop

open System

let timeOfDay = DateTime.Now.ToString("hh:mm:ss")

The F# failwith Function

F# has an failwith function, which when executed prints a string and stops the execution.

let rec sqr n:float = if n<0. then failwith("Cannot compute the square root of a negative number in R") else Math.Sqrt n

Interop from F#

Use #r to reference a DLL .Open the namespace

#r "System.Core.dll"open System.Collections.Genericlet a = HashSet<int>()

F#

F# -> Imperative Programming

F# -> Declarative Programming

C#

A C# program usually consists of statements to

change the program’s state.

Imperative language

An imperative language describes how to finish a

task with exact steps.

Imperative programming

How to make a scrambled egg

Control Flow

Branching with if/else Looping with while/do

Looping with for Handling exceptions

Computation as sequence

X = 3

Y = 7X = 2X+Y

X = 13

Y = 7

State Before Control Flow State After

Focus on how to do

something

Change of state

Procedural programming is a common sub-type

You can have function calls or

sub-routines

Imperative language

Functional Language

A functional-first language, like F#, is more declarative, describing what the program should accomplish.

Computation as calculation

2*3+7 6+7

13

Declarative

Calculate the sum of the first ten integers.

let result = [ 1 .. 10 ] |> List.sum

Declarative

Calculate the sum of the first ten integers.

let result = [ 1 .. 10 ] |> List.reduce (fun x this -> x + this)

Sum of first ten integers (C#)

int sum = 0;for (int i = 1; i <= 10; i++){ sum += i;}

Sum

Variable

C#

C# doesn’t allow the definition of a function outside a class. So the best practice is to create a static function (method) into a class.

Sum of n integers with C#

int sum = 0;int[] numbers = { 2,5,6,3,7,38,555,66 };foreach (var item in numbers){ sum += item;}

Imperative programmingopen System.IO

open System.Net

let url = @"http://mahamudra.it/"// Download the webpagelet req = WebRequest.Create(url)let resp = req.GetResponse()let stream = resp.GetResponseStream()let reader = new StreamReader(stream)let html = reader.ReadToEnd()

Syntactic sugar with C# var url = @"http://mahamudra.it/"; var html = string.Empty; // Download the webpage var req = WebRequest.Create(url); var resp = req.GetResponse(); using (var stream = resp.GetResponseStream()) { using (var reader = new StreamReader (stream)) { html = reader.ReadToEnd(); } }

DRY

Do Not Repeat YourSelf

Procedural Programmingopen System.IO

open System.Net

let getHtml url // Download the webpage

let req = WebRequest.Create(url)let resp = req.GetResponse()let stream = resp.GetResponseStream()let reader = new StreamReader(stream)let html = reader.ReadToEnd()html

But…

Functional IdeasFirst-class Functions / Higher-order Functions•Functions can be passes as arguments to other functions

Purity•Function calls don’t change state

Immutable Data•Data structures cannot be modified

Reference transparency•Function results depend only on its arguments

FP vs OOP

Breaks the problem into «nouns» called objects.

Object Oriented Programming (oop)

Objects inherit from other objects

Object Oriented Programming (oop)

Breaks the problem into «verbs» or actions called

functions.

Functional Programming

F(x) g(x) gof(x)

body

p0 p1 p…

Return f(p1,p2,..)

What’s a function?pnParameters/

values

Name f

•A function f from a set X (the domain) to a set Y (the range) maps each element x in X to a unique element y in Y.•For example, f(x) = x2 maps the set of real numbers into the set of positive real numbers.• i.e., the domain X is the set of all real numbers, the range is the set of positive reals.

Background: Functions

Functions model determinism

X

F(X)

F(X)X’

F(X’)

Per ogni x esiste uno ed un solo y tale che f(x) sia uguale a y

outputs depend predictably on inputs

X’’ F(X’’)

F: x->F(x)

Functional Programming

f(x) g(x)

gof(x)

Functions are «composed» together

g(f(x))x f(x)

x g(f(x))

• If f is a function from X to Y and g is a function from Y to Z, then (g ◦ f ) (x) is a function from X to Z defined

as (g ◦ f ) (x) = g(f (x)), for all x in X

Simply put, it means to replace the x in g(x) with f (x).•Example:• f (x) = x2 + x; g(x) = 2x + 1•g ◦ f = 2*f(x) + 1 = 2(x2 + x ) + 1

Background: Functional Composition

•Example using mathematical functions:• f (x) = x2 + x•g(x) = 2x + 1•g ◦ f = 2(x2 + x ) + 1

•Example using programming language function• int f (x) {x2 + x};• int g(x) {2x + 1};•Now, g(f(x))is {2 * f(x) + 1};

Background: Functional Composition

•Pure functional programming is state-free: no assignment statements.• In other words, no variables, no way to permanently change memory.

•Programs in pure functional languages consist of composite functions; output of each function becomes input to another.•Today, most functional languages have some imperative statements.

Almost functional language

First Class Function

First-class functions

Pure functions Recursion Immutable

variables

Nonstrict evaluation Statements Pattern

matching

First Class FunctionFirst-class functions can either accept another function as an

argument or return afunction.

Higher order functions

Higher order functions are those that take other

functions as parameters or return other functions as their

results.

First Class Functionlet execute fn a = fn(a)val execute : f:('a -> 'b) -> a:'a -> 'b

let result = execute (fun x -> x*x) 5

val result : int = 25

Function types

Pure Functions

First-class functions

Pure functions Recursion Immutable

variables

Nonstrict evaluation Statements Pattern

matching

Pure functions

Pure functions are functions that have no side effects. Also called referentially transparent functions.

Side Effects[<EntryPoint>]let main argv = let result = execute (fun x->x*x) 5 printfn "%d" result 0 // return an integer exit code

Void vs UnitUnit Types// define a function returns unitlet f x = () // f : 'a -> unit// use ignore to throw away the keyboard input and f2 returns unitlet f2 () = System.Console.ReadKey() |> ignore

Side effectsf(5) + f(5) <> 2*f(5)

Side effects requires a more complex model, and thus makes it harder to understand the software

Recursion

First-class functions

Pure functions

Recursion Immutable variables

RecursionA recursive function is a function that calls itself.

ExampleThe factorial function “!” on natural numbers0! = 1n! = n · (n − 1)!, n > 0Recursion corresponds to loops in ordinary programming

Factoriallet rec fac n = if n = 0 then 1 else n*fac (n-1)

Immutable variables

First-class functions

Pure functions

Recursion Immutable variables

ImmutabilityThe value assigned to a

variable or a structure can’t be change once initialized.

Value not Variable

.NET types

Immutability

integers strings date time

F#

Immutability

Seq Set List

In imperative programming, variables are used to denote memory locations:

x = x + 1means “Update the program state by adding 1 to the value stored in the memory cell named x and storing the sum back in the memory cell.”x is used two ways: as an r-value and an l-value

Semantics of Variables

• Functional languages adopt the mathematical notion of a variable as something that represents an expression.• There is no association with a memory location or

modification of a variable’s value.• So in functional languages a variable represents an

immutable value. • Since variables don’t get updated, there’s no concept

of assignment and consequently no notion of program state.

Semantics of Variables

Practical motivation public class Utility { static int n = 1; public static int fun (int x) { n += 1; return n+x; } }

Fun isn’t funThis means that fun returns different values for different calls, even when called with the same argument.Much harder to reason mathematically about such functions: for instance, these values are different:

var result = Utility.fun(10) + Utility.fun(10);var result = 2* Utility.fun(10) ;

Nonstrict evaluation

First-class functions

Pure functions

Recursion Immutable variables

Nonstrict evaluationNonstrict means that we can have a variable that does not get assigned (computed) untilthe first time it is referenced.

Lazy loading (C#)int[] list = {1,34,5,666,76};var even_terms = from p in list where (p % 2==0) select p;var it_does_not_matter = 1;var count_even_terms = even_terms.Count();

it_does_not_matter.Dump();count_even_terms.Dump();

Statements

First-class functions

Pure functions

Recursion Immutable variables

StatementsStatements are evaluable pieces of code that have a

return value.

Statements

First-class functions

Pure functions

Recursion Immutable variables

Match vs Case

MatchF# has a case constructmatch expr with

| pattern1 -> expr1| pattern2 -> expr2....

Pattern MatchingSelect case

let isOdd number = match number % 2 with| 0 -> false| _ -> true

* “_” is a “wildcard”, matches anything

Factoriallet rec fac n = match n with

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

Sum of first ten integers let rec sum lst = match lst with | [] -> 0 | head::tail->head+ sum tail let result = sum [1..10]

Sum of n integers let rec sum lst = match lst with | [] -> 0 | head::tail->head+ sum tail let result = sum [2;5;6;3;7;38;555;66]

Takelet rec take n lista =

match (n,lista) with| (0,_) -> []| (_,[]) -> failwith "taking too many"| (_,x::ls) -> x :: take (n-1) ls