SlideShare a Scribd company logo
1 of 82
F#
F#
F# is a multiparadigm
programming 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 Entities
F# manages to find types automatically:
This is called type inference
For instance
let pi = 3.14159
Here, pi will automatically obtain the type
float since 3.14159 can only have type float
Explicit Type Declarations
let sum x y = x + y
F# will assume that “+” is plus on the
type int.
let sum x y = (x + y) : float
It 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.Generic
let 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 = 7
X = 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
Frequently
combined with
object-oriented
programming
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 programming
open System.IO
open System.Net
let url = @"http://mahamudra.it/"
// 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()
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 Programming
open 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 Ideas
First-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
Object Oriented Programming (oop)
Object Oriented Programming (oop)
Functional Programming
F(x) g(x) gof(x)
body
p0 p1 p…
Return
f(p1,p2,..)
What’s a function?
pn
Parameters/
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)
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 Function
First-class functions can
either accept another
function as an argument or
return a
function.
Higher order functions
Higher order functions
are those that take other
functions as parameters or
return other functions as
their results.
First Class Function
let 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 Unit
Unit Types
// define a function returns unit
let f x = () // f : 'a -> unit
// use ignore to throw away the keyboard
input and f2 returns unit
let f2 () = System.Console.ReadKey() |>
ignore
Side effects
f(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
Nonstrict
evaluation
Statements
Pattern
matching
Recursion
A recursive function is a
function that calls itself.
Example
The factorial function “!” on
natural numbers
0! = 1
n! = n · (n − 1)!, n > 0
Recursion corresponds to loops in ordinary programming
Factorial
let rec fac n =
if n = 0 then 1 else n*fac (n-1)
Immutable variables
First-class
functions
Pure
functions
Recursion
Immutable
variables
Nonstrict
evaluation
Statements
Pattern
matching
Immutability
The 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 + 1
means “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 fun
This 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
evaluation
Statements
Pattern
matching
Nonstrict evaluation
Nonstrict means that we can
have a variable that does not
get assigned (computed) until
the 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
Nonstrict
evaluation
Statements
Pattern
matching
Statements
Statements are evaluable
pieces of code that have a
return value.
Statements
First-class
functions
Pure
functions
Recursion
Immutable
variables
Nonstrict
evaluation
Statements
Pattern
matching
Match vs Case
Match
F# has a case construct
match expr with
| pattern1 -> expr1
| pattern2 -> expr2
....
Pattern Matching
Select case
let isOdd number =
match number % 2 with
| 0 -> false
| _ -> true
* “_” is a “wildcard”, matches anything
Factorial
let 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]
Take
let rec take n lista =
match (n,lista) with
| (0,_) -> []
| (_,[]) -> failwith "taking too many"
| (_,x::ls) -> x :: take (n-1) ls

More Related Content

What's hot

Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
Sami Said
 
Introduction of bison
Introduction of bisonIntroduction of bison
Introduction of bison
vip_du
 

What's hot (19)

Python advance
Python advancePython advance
Python advance
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Intro to Functional Reactive Programming In Scala
Intro to Functional Reactive Programming In ScalaIntro to Functional Reactive Programming In Scala
Intro to Functional Reactive Programming In Scala
 
Functions
FunctionsFunctions
Functions
 
Ch6
Ch6Ch6
Ch6
 
Functions
Functions Functions
Functions
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
C language basics
C language basicsC language basics
C language basics
 
Learn C
Learn CLearn C
Learn C
 
User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.User_Defined_Functions_ppt_slideshare.
User_Defined_Functions_ppt_slideshare.
 
Lexical analysis-using-lex
Lexical analysis-using-lexLexical analysis-using-lex
Lexical analysis-using-lex
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Actors and functional_reactive_programming
Actors and functional_reactive_programmingActors and functional_reactive_programming
Actors and functional_reactive_programming
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Introduction of bison
Introduction of bisonIntroduction of bison
Introduction of bison
 

Similar to Intro f# functional_programming

Similar to Intro f# functional_programming (20)

Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
Scala functions
Scala functionsScala functions
Scala functions
 
F# 101
F# 101F# 101
F# 101
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Dev Concepts: Functional Programming
Dev Concepts: Functional ProgrammingDev Concepts: Functional Programming
Dev Concepts: Functional Programming
 
Special topics in finance lecture 2
Special topics in finance   lecture 2Special topics in finance   lecture 2
Special topics in finance lecture 2
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
Functional go
Functional goFunctional go
Functional go
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Functional Objects in Ruby: new horizons  – Valentine OstakhFunctional Objects in Ruby: new horizons  – Valentine Ostakh
Functional Objects in Ruby: new horizons – Valentine Ostakh
 
Function
FunctionFunction
Function
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Erlang session1
Erlang session1Erlang session1
Erlang session1
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 

Intro f# functional_programming