SlideShare une entreprise Scribd logo
1  sur  37
Télécharger pour lire hors ligne
Dmitri Nesteruk
dmitrinesteruk @ gmail.com
http://spbalt.net
“…a programming paradigm that
treats computation as the evaluation
of mathematical functions and
avoids state and mutable data”
                                       —Wikipedia
  Higher-order functions
   
   i => j => f(j)

   Pure functions
   
   Immutability
   
   No side effects

   (Tail) recursion
   
   let f(x) = …; f(x-1);

   Pattern matching
  Math
   
   Probabilistic models

   Symbolic processing (parsing/lexing)
   
   Symbolic differentiation
   
   Circuit verification
  Multi-paradigm language in .NET stack
   
   Functional
   
   Imperative

   Performance similar to C#

   Interactive console

   Support in Visual Studio
   
   Debugger
   
   Editor

   Mono support
  #light 
    printfn “Hello, F#!” 


   #light 
    Light syntax – cuts down on ceremony when
    writing code
  
       Indentation instead of begin/end
  
       Use of in,done keywords not required
  
       No semicolons
  
       Currently mandatory – will be default in future
  printfn “Hello, F#”
    Writes a line to the console
   
   A top-level binding (like a global function)
   
   Part of FSharp.Core
     
   Referenced implicitly
   
   Appears in a generated _main() 
   
   Can “Go To Definition”
  Can do it with a function

  let sayHello = 
    printfn “Hello, F#!” 
  sayHello 


   Or pass a parameter

  let sayHello s = 
    printfn s 
  sayHello "Hello, F#!" 
  Application operator |> (forward pipe)

  let sayHello s = 
    s |> printfn // same as printfn s 


   Explicit types

  let length a = a.Length; // not ok 
  let length (a:string) = 
    a.Length // ok
  Recursive definition

  let rec factorial n = 
    if n <= 1 then 1  
    else n * factorial(n‐1) 


   Mutual recursion 

  let rec funcA x = 1 + funcB(x) 
  and funcB x = 1 – funcA(x) 
  One statement per line, use in for more
   
   let powerOf4 x = 
         let y = x * x in y * y 

   No implicit conversions
   
   let GetXName xname = 
         XName.op_Implicit(xname) 

   Aggressive strong typing
   
   let o:obj = “test”; // fails 
   
   let o = box “test”; // ok 

   Mutability must be explicit
   
   mutable keyword
   
   variable <‐ value to assign
  Clever switch statement

   Can match values of any type


   let matchMe x = 
      match x with 
      | 1 ‐> printfn "one"  
      | 2 ‐> printfn "two"  
      | _ ‐> printfn "something else"


   Cannot bind same pattern element twice
   
   Cannot match (x, x)
   
   Can match (x, y) when x = y
  Tuple

     Option value

     Array

     Sequence

     List
  Contains several values of any types

   No more Pair<T,U> etc. classes


   let sumAndProduct a b = 
      (a+b, a*b)


   let (s, p) = sumAndProduct 2 3 
    printfn "%d %d" s p 


   Tuples use comma ,
    Other structures use semicolon ;
  null is typically not used with F# types

   Presence or absence can be discriminated with
    an option value, which is
   
   None 
   
   Some of 'a 

   Use pattern matching 

  match x with 
  | Some(name) ‐> printfn name 
  | None ‐> printfn “anonymous” 
  Your typical CLR array

  let people = [|  
    “john”;  
    “jane”;  
    “jack”  
  |] 


   people.Length 
   
   yields 3
  Enumerable values
    
   let a = seq [1; 2; 3] 
    
   let b = seq { for i in 1 .. 10 ‐> (i*i) } 

   Lazy-inited
    
   seq { 1 .. 10000000 } 

   Step
    
   seq { 1 .. 2 .. 10 } 
    
   yields 1, 3, 5, 7, 9

   Strings are char sequences
    
   printfn "%d" (Seq.length "Hello") 

   Iterated with for .. in .. do
    
   for i in mySeq do printfn “%d” i 
  Linked list of values

  [1; 2; 3]


   Has head and tail
   
       Head is the first element 
   
       Tail is everything else 
   
       [] is the empty list
   
       [1, 2, 3] has length of 1:)
  let a = [1; 2; 3] 

     Head = 1 

     Tail = [2; 3] 

     let b = 0 :: a 
     
   [0; 1; 2; 3] 

   let c = a @ b 
     
   [1; 2; 3; 0; 1; 2; 3] 
  let rec sumAll myList = 
      match myList with 
      | h :: t ‐> head + sumAll(t) 
      | [] ‐> 0


   let rec nonZero myList = 
      match myList with 
      | 0 :: t ‐> 1 :: nonZero t 
      | h :: t ‐> h :: nonZero t 
      | [] ‐> [] 


   let rec htmlDecode text = 
      match text with 
      | ‘&’ :: ‘g’ :: ‘t’ :: ‘;’ :: tail ‐> 
          ‘>’ :: htmlDecode tail // and so on   
  A non-exhaustive match will throw a
    MatchFailureException 


   Patterns can be grouped
   
   match person with 
       | a :: (b :: c as subGroup) ‐> 
         match subGroup with 
  Anonymous functions

     Functional composition

     Partial application

     Memoization
  A way of defining nameless functions
   
   fun x ‐> x * 2 

   Can be passed as parameter

   Can be bound, i.e.
   
   let square = fun x ‐> x * x 
  Used to provide LINQ-like features to lists and sequences

   let myList = [1; 2; 3]

   List.iter (fun f ‐> printfn “%d” f) myList 
    
   Iterates through the collection

   List.map (fun f ‐> f + 1) myList 
    
   Returns a modified list [2; 3; 4] – LINQ Select()

   List.filter (fun f ‐> f % 2 = 0) myList 
    
   Returns only odd elements – LINQ Where()

   Other useful functions (e.g., List.to_array)

   Similar features in seq 
  Operators can be piped
   
   values |> List.map (fun f ‐> f + 1) 
              |> List.filter(fun f ‐> f > 0) 


   And functionally composed
   
   let even = List.filter  
                       (fun f ‐> f % 2 = 0) 
       let positive = List.filter 
                       (fun f ‐> f > 0) 
       let evenAndPos = even >> positive 
   
   evenAndPos [1; ‐2; 4] 
     
   yields [4]
  let squareThis x = 
      x * x  

   let addFive x = 
      x + 5 

   5 |> squareThis |> addFive 
  
   yields 30

   let squareAndAddFive = 
      squareThis >> addFive 

   squareThisAndAddFive 5 
  
   yields 30
  let shift (dx, dy) (px, py) =  
      (px + dx, py + dy) 


   shift (1, 0) (100, 100) 
  
   result is (101, 100)


   let shiftRight = shift (1, 0)


   shiftRight (100, 100) 
  
   result is (101, 100)
  Keep a lookaside table of computed values


   let rec fib n = 
      if n <= 2 then 1 
      else fib(n‐1) + fib(n‐2) 


   Computed values wasted
   
   Why not cache them?
  let fibFast n = 
      let t = new Dictionary<int,int>() 
      let rec fibCached n = 
        if t.ContainsKey(n) then t.[n] 
        else if n <= 2 then 1 
        else let res =  
          fibCached(n‐1) + fibCached(n‐2) 
          t.Add(n,res) 
          res 
      fibCached n 
  Computation expressions = workflows
   
   builder { expression }

   Usage
   
   General programming (e.g., seq { … })
   
   Asynchronous workflows
   
   Database queries
  Define a builder type

   Computation expression constructs map onto
    the builder methods (are de-sugared)
   
   E.g., let a = b in c  maps onto
   
   builder.Let(b, (fun a ‐> c)) 

   Builder affects behavior of contained
    expressions
   
   E.g., makes them asynchronous
  Many .NET APIs feature Begin/End pairs
   
   E.g., BeginGetResponse/EndGetResponse

   Frameworks make code look sequential
   
   Abstracting away Begin/End calls
   
   C#  AsyncEnumerator from PowerThreading
   
   F#  Async workflows

   Goals
   
   Begin an asynchronous operation
   
   Resume execution when it’s done
   
   Let threads interleave
  Async<'a> 
   
   Represents a result of 'a computed in the future

   This class needs to know about begin/end
    pairs
   
   Extends existing types with XXXAsync() calls
   
   type WebRequest with 
         member x.GetResponseAsync() =  
           Async.BuildPrimitive( 
             x.BeginGetResponse, 
             x.EndGetResponse) 
  Once Async knows about Begin/End elements
    we can use the async { … } workflow
  
   let download url = 
        async { 
          let rq = WebRequest.Create(url)    
          let! resp = rq.GetResponseAsync() 
          use s = resp.GetResponseStram() 
          use r = new StreamReader(s) 
          r.ReadToEnd() 
        } 
  
   let! fires off BeginGetResponse() asynchronously
  
   and waits on completion
  let urls = [ 
      “http://spbalt.net”; 
      “http://sp.ineta.ru”; 
      “http://altdotnet.org” ]


   Spawn one-by-one
   
   for url in urls do 
         Async.Spawn(download(url))


   Send all at once
   
   urls |> List.map(fun f ‐> download(f)) 
            |> Async.Parallel |> Async.Run 
  Foundations of F#
    Robert Pickering


   Expert F#
    Don Syme et al.


   F# for Scientists
    Jon Harrop
Functional Programming in F#

Contenu connexe

Tendances

Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programmingScott Wlaschin
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
Advance python programming
Advance python programming Advance python programming
Advance python programming Jagdish Chavan
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)IoT Code Lab
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & ImportMohd Sajjad
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusDhivyaSubramaniyam
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasserySHAMJITH KM
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Philip Schwarz
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 

Tendances (20)

Reactive fsharp
Reactive fsharpReactive fsharp
Reactive fsharp
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
 
Time for Functions
Time for FunctionsTime for Functions
Time for Functions
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Ch8a
Ch8aCh8a
Ch8a
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 

En vedette

En vedette (18)

Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
AOP via PIAB and Unity
AOP via PIAB and UnityAOP via PIAB and Unity
AOP via PIAB and Unity
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
ReSharper Architecture & Extensions
ReSharper Architecture & ExtensionsReSharper Architecture & Extensions
ReSharper Architecture & Extensions
 
Victor CG Erofeev - Metro UI
Victor CG Erofeev - Metro UIVictor CG Erofeev - Metro UI
Victor CG Erofeev - Metro UI
 
Introduction to Programming Bots
Introduction to Programming BotsIntroduction to Programming Bots
Introduction to Programming Bots
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
 
Проект X2C
Проект X2CПроект X2C
Проект X2C
 
Domain Transformations
Domain TransformationsDomain Transformations
Domain Transformations
 
Distributed Development
Distributed DevelopmentDistributed Development
Distributed Development
 
Monte Carlo C++
Monte Carlo C++Monte Carlo C++
Monte Carlo C++
 
C# Tricks
C# TricksC# Tricks
C# Tricks
 
Code Generation
Code GenerationCode Generation
Code Generation
 
Design Patterns in .Net
Design Patterns in .NetDesign Patterns in .Net
Design Patterns in .Net
 
Web mining
Web miningWeb mining
Web mining
 
ReSharper Presentation for NUGs
ReSharper Presentation for NUGsReSharper Presentation for NUGs
ReSharper Presentation for NUGs
 
YouTrack: Not Just an Issue Tracker
YouTrack: Not Just an Issue TrackerYouTrack: Not Just an Issue Tracker
YouTrack: Not Just an Issue Tracker
 
Data mapping tutorial
Data mapping tutorialData mapping tutorial
Data mapping tutorial
 

Similaire à Functional Programming in F#

Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharpDaniele Pozzobon
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabMohan Raj
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Guy Lebanon
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
In the Notes on Programming Language Syntax page, an example par.docx
In the Notes on Programming Language Syntax page, an example par.docxIn the Notes on Programming Language Syntax page, an example par.docx
In the Notes on Programming Language Syntax page, an example par.docxmecklenburgstrelitzh
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
F# and Reactive Programming for iOS
F# and Reactive Programming for iOSF# and Reactive Programming for iOS
F# and Reactive Programming for iOSBrad Pillow
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 

Similaire à Functional Programming in F# (20)

Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
C# programming
C# programming C# programming
C# programming
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
In the Notes on Programming Language Syntax page, an example par.docx
In the Notes on Programming Language Syntax page, an example par.docxIn the Notes on Programming Language Syntax page, an example par.docx
In the Notes on Programming Language Syntax page, an example par.docx
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python basic
Python basicPython basic
Python basic
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
F# and Reactive Programming for iOS
F# and Reactive Programming for iOSF# and Reactive Programming for iOS
F# and Reactive Programming for iOS
 
Python
PythonPython
Python
 
Testing for share
Testing for share Testing for share
Testing for share
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Python programming
Python  programmingPython  programming
Python programming
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 

Plus de Dmitri Nesteruk

Good Ideas in Programming Languages
Good Ideas in Programming LanguagesGood Ideas in Programming Languages
Good Ideas in Programming LanguagesDmitri Nesteruk
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern ObservationsDmitri Nesteruk
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETDmitri Nesteruk
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++Dmitri Nesteruk
 
Converting Managed Languages to C++
Converting Managed Languages to C++Converting Managed Languages to C++
Converting Managed Languages to C++Dmitri Nesteruk
 
Dynamics CRM Data Integration
Dynamics CRM Data IntegrationDynamics CRM Data Integration
Dynamics CRM Data IntegrationDmitri Nesteruk
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and ParallelizationDmitri Nesteruk
 

Plus de Dmitri Nesteruk (9)

Good Ideas in Programming Languages
Good Ideas in Programming LanguagesGood Ideas in Programming Languages
Good Ideas in Programming Languages
 
Design Pattern Observations
Design Pattern ObservationsDesign Pattern Observations
Design Pattern Observations
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NET
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
Converting Managed Languages to C++
Converting Managed Languages to C++Converting Managed Languages to C++
Converting Managed Languages to C++
 
Tpl DataFlow
Tpl DataFlowTpl DataFlow
Tpl DataFlow
 
Developer Efficiency
Developer EfficiencyDeveloper Efficiency
Developer Efficiency
 
Dynamics CRM Data Integration
Dynamics CRM Data IntegrationDynamics CRM Data Integration
Dynamics CRM Data Integration
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 

Dernier

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Dernier (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

Functional Programming in F#

  • 1. Dmitri Nesteruk dmitrinesteruk @ gmail.com http://spbalt.net
  • 2. “…a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data” —Wikipedia
  • 3.   Higher-order functions   i => j => f(j)   Pure functions   Immutability   No side effects   (Tail) recursion   let f(x) = …; f(x-1);   Pattern matching
  • 4.   Math   Probabilistic models   Symbolic processing (parsing/lexing)   Symbolic differentiation   Circuit verification
  • 5.   Multi-paradigm language in .NET stack   Functional   Imperative   Performance similar to C#   Interactive console   Support in Visual Studio   Debugger   Editor   Mono support
  • 6.   #light  printfn “Hello, F#!”    #light  Light syntax – cuts down on ceremony when writing code   Indentation instead of begin/end   Use of in,done keywords not required   No semicolons   Currently mandatory – will be default in future
  • 7.   printfn “Hello, F#” Writes a line to the console   A top-level binding (like a global function)   Part of FSharp.Core   Referenced implicitly   Appears in a generated _main()    Can “Go To Definition”
  • 8.   Can do it with a function let sayHello =    printfn “Hello, F#!”  sayHello    Or pass a parameter let sayHello s =    printfn s  sayHello "Hello, F#!" 
  • 9.   Application operator |> (forward pipe) let sayHello s =    s |> printfn // same as printfn s    Explicit types let length a = a.Length; // not ok  let length (a:string) =    a.Length // ok
  • 10.   Recursive definition let rec factorial n =    if n <= 1 then 1     else n * factorial(n‐1)    Mutual recursion  let rec funcA x = 1 + funcB(x)  and funcB x = 1 – funcA(x) 
  • 11.   One statement per line, use in for more   let powerOf4 x =    let y = x * x in y * y    No implicit conversions   let GetXName xname =    XName.op_Implicit(xname)    Aggressive strong typing   let o:obj = “test”; // fails    let o = box “test”; // ok    Mutability must be explicit   mutable keyword   variable <‐ value to assign
  • 12.   Clever switch statement   Can match values of any type   let matchMe x =    match x with    | 1 ‐> printfn "one"     | 2 ‐> printfn "two"     | _ ‐> printfn "something else"   Cannot bind same pattern element twice   Cannot match (x, x)   Can match (x, y) when x = y
  • 13.   Tuple   Option value   Array   Sequence   List
  • 14.   Contains several values of any types   No more Pair<T,U> etc. classes   let sumAndProduct a b =    (a+b, a*b)   let (s, p) = sumAndProduct 2 3  printfn "%d %d" s p    Tuples use comma , Other structures use semicolon ;
  • 15.   null is typically not used with F# types   Presence or absence can be discriminated with an option value, which is   None    Some of 'a    Use pattern matching  match x with  | Some(name) ‐> printfn name  | None ‐> printfn “anonymous” 
  • 16.   Your typical CLR array let people = [|     “john”;     “jane”;     “jack”   |]    people.Length    yields 3
  • 17.   Enumerable values   let a = seq [1; 2; 3]    let b = seq { for i in 1 .. 10 ‐> (i*i) }    Lazy-inited   seq { 1 .. 10000000 }    Step   seq { 1 .. 2 .. 10 }    yields 1, 3, 5, 7, 9   Strings are char sequences   printfn "%d" (Seq.length "Hello")    Iterated with for .. in .. do   for i in mySeq do printfn “%d” i 
  • 18.   Linked list of values [1; 2; 3]   Has head and tail   Head is the first element    Tail is everything else    [] is the empty list   [1, 2, 3] has length of 1:)
  • 19.   let a = [1; 2; 3]    Head = 1    Tail = [2; 3]    let b = 0 :: a    [0; 1; 2; 3]    let c = a @ b    [1; 2; 3; 0; 1; 2; 3] 
  • 20.   let rec sumAll myList =    match myList with    | h :: t ‐> head + sumAll(t)    | [] ‐> 0   let rec nonZero myList =    match myList with    | 0 :: t ‐> 1 :: nonZero t    | h :: t ‐> h :: nonZero t    | [] ‐> []    let rec htmlDecode text =    match text with    | ‘&’ :: ‘g’ :: ‘t’ :: ‘;’ :: tail ‐>        ‘>’ :: htmlDecode tail // and so on   
  • 21.   A non-exhaustive match will throw a MatchFailureException    Patterns can be grouped   match person with  | a :: (b :: c as subGroup) ‐>    match subGroup with 
  • 22.   Anonymous functions   Functional composition   Partial application   Memoization
  • 23.   A way of defining nameless functions   fun x ‐> x * 2    Can be passed as parameter   Can be bound, i.e.   let square = fun x ‐> x * x 
  • 24.   Used to provide LINQ-like features to lists and sequences   let myList = [1; 2; 3]   List.iter (fun f ‐> printfn “%d” f) myList    Iterates through the collection   List.map (fun f ‐> f + 1) myList    Returns a modified list [2; 3; 4] – LINQ Select()   List.filter (fun f ‐> f % 2 = 0) myList    Returns only odd elements – LINQ Where()   Other useful functions (e.g., List.to_array)   Similar features in seq 
  • 25.   Operators can be piped   values |> List.map (fun f ‐> f + 1)         |> List.filter(fun f ‐> f > 0)    And functionally composed   let even = List.filter                   (fun f ‐> f % 2 = 0)  let positive = List.filter                  (fun f ‐> f > 0)  let evenAndPos = even >> positive    evenAndPos [1; ‐2; 4]    yields [4]
  • 26.   let squareThis x =    x * x     let addFive x =    x + 5    5 |> squareThis |> addFive    yields 30   let squareAndAddFive =    squareThis >> addFive    squareThisAndAddFive 5    yields 30
  • 27.   let shift (dx, dy) (px, py) =     (px + dx, py + dy)    shift (1, 0) (100, 100)    result is (101, 100)   let shiftRight = shift (1, 0)   shiftRight (100, 100)    result is (101, 100)
  • 28.   Keep a lookaside table of computed values   let rec fib n =    if n <= 2 then 1    else fib(n‐1) + fib(n‐2)    Computed values wasted   Why not cache them?
  • 29.   let fibFast n =    let t = new Dictionary<int,int>()    let rec fibCached n =      if t.ContainsKey(n) then t.[n]      else if n <= 2 then 1      else let res =         fibCached(n‐1) + fibCached(n‐2)        t.Add(n,res)        res    fibCached n 
  • 30.   Computation expressions = workflows   builder { expression }   Usage   General programming (e.g., seq { … })   Asynchronous workflows   Database queries
  • 31.   Define a builder type   Computation expression constructs map onto the builder methods (are de-sugared)   E.g., let a = b in c  maps onto   builder.Let(b, (fun a ‐> c))    Builder affects behavior of contained expressions   E.g., makes them asynchronous
  • 32.   Many .NET APIs feature Begin/End pairs   E.g., BeginGetResponse/EndGetResponse   Frameworks make code look sequential   Abstracting away Begin/End calls   C#  AsyncEnumerator from PowerThreading   F#  Async workflows   Goals   Begin an asynchronous operation   Resume execution when it’s done   Let threads interleave
  • 33.   Async<'a>    Represents a result of 'a computed in the future   This class needs to know about begin/end pairs   Extends existing types with XXXAsync() calls   type WebRequest with    member x.GetResponseAsync() =       Async.BuildPrimitive(        x.BeginGetResponse,        x.EndGetResponse) 
  • 34.   Once Async knows about Begin/End elements we can use the async { … } workflow   let download url =    async {      let rq = WebRequest.Create(url)         let! resp = rq.GetResponseAsync()      use s = resp.GetResponseStram()      use r = new StreamReader(s)      r.ReadToEnd()    }    let! fires off BeginGetResponse() asynchronously   and waits on completion
  • 35.   let urls = [    “http://spbalt.net”;    “http://sp.ineta.ru”;    “http://altdotnet.org” ]   Spawn one-by-one   for url in urls do    Async.Spawn(download(url))   Send all at once   urls |> List.map(fun f ‐> download(f))       |> Async.Parallel |> Async.Run 
  • 36.   Foundations of F# Robert Pickering   Expert F# Don Syme et al.   F# for Scientists Jon Harrop