intro f# functional_programming
TRANSCRIPT
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
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
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
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>()
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.
Declarative
Calculate the sum of the first ten integers.
let result = [ 1 .. 10 ] |> List.reduce (fun x this -> x + this)
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(); } }
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
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
Breaks the problem into «verbs» or actions called
functions.
Functional Programming
F(x) g(x) gof(x)
•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)
• 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
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
ExampleThe factorial function “!” on natural numbers0! = 1n! = n · (n − 1)!, n > 0Recursion corresponds to loops in ordinary programming
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 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();
Pattern MatchingSelect case
let isOdd number = match number % 2 with| 0 -> false| _ -> true
* “_” is a “wildcard”, matches anything
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]