SlideShare uma empresa Scribd logo
1 de 20
What the Math Geeks Don't Want You to Know about F# Tips for OvercomingObstacles to Learning F# August 2010 Kevin Hazzard, C# MVP
What This Talk Is & Is Not This talk does not intend to teach F# deeply This talk is for C# / VB.NET programmers trying to answer the questions: Why should I care about functional languages? What makes F# worth learning? What's going to slow me down on the journey?
What makes a language functional? Compositional and often expression-oriented Supports functions as first-class types Often promotes lazy evaluation Extensive use of higher-order functions Avoids memory and I/O side-effects Prefers recursion over iteration Excellent for concurrent programming May have polymorphic data types withextensive pattern matching capabilities
A Teaching Example type BinaryTree<'a> =      | Leaf of 'a      | Node of BinaryTree<'a> * BinaryTree<'a>
Obstacle #1 Pattern matching is foreign and pervasive. Pattern matching is at the core of F# When learning F#, focus on every pattern matching example you can find Start with the simple ones, e.g. discriminated unions, move up and out Treat this learning as a block and learn it deeply, in a very focused way
Obstacle #2 Type inference makes F# feel like a scripting language. If you're a Pythonista, you will feel at home writing F# - the types get out of your way If not… Watch carefully for inferred types, especially while you are learning – use the FSI REPL a lot Use automatic generalization to reduce code volume and increase simplicity
Automatic Generalization No obstacle but something to be aware of What type does this operate on? let max a b = if a > b then a else b F# automatically generalizes complete expressions when it can
Recursion – Port This to F# public inthcf( intx, inty ) { int result = 0;     while (result == 0) {         if (x < y) { y %= x;             if (y == 0)                 result = x;         }         else { x %= y;             if (x == 0)                 result = y;         }     }     return result; }
Isn't This Succinct? let rechcf a b =if a = 0 then belifb = 0 then aelif a < b then hcf a (b % a)else hcf (a % b) b
Tail Recursion Optimization Recursive functions that do no extra work after the recursion can often be converted to while loops F# does this automatically if the code is structured to allow for it The JITter will sometimes do this on compiled code No guarantees though
Obstacle #3 Recursion may be at odds with your belief system.  Many of us were taught to fear recursion Stop thinking that way Every time you write an iteration think,"Could this be done with recursion instead?" Write your F# code so that it is tail optimizable
Workflows (Computation Expressions) Bind Delay Return ReturnFrom Combine For TryFinally TryWith Using While YieldFrom Zero
Obstacle #4 Workflows are central to F# and tough to understand. Think of workflows like little Domain Specific Languages (DSL) Builders are like AOP-enabled classes, allowing you to hook and define those 12 core functions When the F# code in the computation expression is evaluated, your code gets to direct the work Focus on understanding the built-in async workflow
VS Gallery F# Templates When you first look at the F# templates in VS 2010, you may be underwhelmed The F# team and others are always adding F# templates to ease development Daniel Mohl (@dmohl) has written some excellent templates that are available in the online gallery
Obstacle #5 You must rewire your brain a bit to learn F#. F# is part of the .NET ecosystem Great tooling in Visual Studio 2010 Full access to all .NET types and members Seamless access to & from C# and VB.NET F# is multi-paradigm Emphasizes data immutability and the evaluation of expressions But also supports traditional OOP concepts
Don't Get Hung Up On Terms Lambda Calculus Turing Completeness Universal Computer Endofunctors Cata/Ana-morphism Co-algebras Category Theory "How does this help me to write better software?"
Stuff That Is Important Composition / Currying Pattern Matching Type inference Immutability Side-effects Recursion Workflows
Obstacle #6 Functional programming is a new fad. It will pass. Anyone want to guess how long functional programming has been around? OOP dominated because it was the best way to reduce complexity and promote reuse in CPU-bound systems Functional languages are leader languages Data structures Message and event passing Dynamic typing and type inferencing Generics Garbage collection
The History of F# Started in 2002 in Microsoft Research Based on languages like ML and OCaml Influenced great stuff in .NET Generics LINQ Visual Studio support in versions 2005 & 2008 Became a first-class language citizen inVisual Studio 2010
Demo Check out the F# Samplescode.msdn.microsoft.com/fsharpsamples Explore Tutorial.fs with Alt + Enter Samples101

Mais conteúdo relacionado

Mais procurados

Naming guidelines for professional programmers
Naming guidelines for professional programmersNaming guidelines for professional programmers
Naming guidelines for professional programmersPeter Hilton
 
An Introduction to FSharp
An Introduction to FSharpAn Introduction to FSharp
An Introduction to FSharpHoracio Nuñez
 
Writing clean and maintainable code
Writing clean and maintainable codeWriting clean and maintainable code
Writing clean and maintainable codeMarko Heijnen
 
Object Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert HarleObject Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert Harlesuthi
 
Fine tuning large LMs
Fine tuning large LMsFine tuning large LMs
Fine tuning large LMsSylvainGugger
 
CS152 Programming Paradigm
CS152 Programming Paradigm CS152 Programming Paradigm
CS152 Programming Paradigm Kaya Ota
 
Mastering Perl
Mastering PerlMastering Perl
Mastering Perlnuhabecobu
 
How to name things: the hardest problem in programming
How to name things: the hardest problem in programmingHow to name things: the hardest problem in programming
How to name things: the hardest problem in programmingPeter Hilton
 
Dynamic C# and a New World of Possibilities
Dynamic C# and a New World of PossibilitiesDynamic C# and a New World of Possibilities
Dynamic C# and a New World of PossibilitiesChicago ALT.NET
 
Final requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary ClemenceFinal requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary Clemenceclemencebonifacio
 
Deep Learning for Machine Translation - A dramatic turn of paradigm
Deep Learning for Machine Translation - A dramatic turn of paradigmDeep Learning for Machine Translation - A dramatic turn of paradigm
Deep Learning for Machine Translation - A dramatic turn of paradigmMeetupDataScienceRoma
 
How to write maintainable code
How to write maintainable codeHow to write maintainable code
How to write maintainable codePeter Hilton
 
Script writing (2)
Script writing (2)Script writing (2)
Script writing (2)lenteraide
 
A Pragmatic Approach
A Pragmatic ApproachA Pragmatic Approach
A Pragmatic ApproachHakanCanpek
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming LanguageStefanoTermini3
 
TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...
TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...
TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...TCUK Conference
 
Py con 2012 my presentation
Py con 2012 my presentationPy con 2012 my presentation
Py con 2012 my presentationgadha145
 

Mais procurados (20)

Naming guidelines for professional programmers
Naming guidelines for professional programmersNaming guidelines for professional programmers
Naming guidelines for professional programmers
 
An Introduction to FSharp
An Introduction to FSharpAn Introduction to FSharp
An Introduction to FSharp
 
Writing clean and maintainable code
Writing clean and maintainable codeWriting clean and maintainable code
Writing clean and maintainable code
 
Object Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert HarleObject Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert Harle
 
Fine tuning large LMs
Fine tuning large LMsFine tuning large LMs
Fine tuning large LMs
 
CS152 Programming Paradigm
CS152 Programming Paradigm CS152 Programming Paradigm
CS152 Programming Paradigm
 
Mastering Perl
Mastering PerlMastering Perl
Mastering Perl
 
How to name things: the hardest problem in programming
How to name things: the hardest problem in programmingHow to name things: the hardest problem in programming
How to name things: the hardest problem in programming
 
Dynamic C# and a New World of Possibilities
Dynamic C# and a New World of PossibilitiesDynamic C# and a New World of Possibilities
Dynamic C# and a New World of Possibilities
 
The Art Of C
The Art Of CThe Art Of C
The Art Of C
 
Final requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary ClemenceFinal requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary Clemence
 
Deep Learning for Machine Translation - A dramatic turn of paradigm
Deep Learning for Machine Translation - A dramatic turn of paradigmDeep Learning for Machine Translation - A dramatic turn of paradigm
Deep Learning for Machine Translation - A dramatic turn of paradigm
 
How to write maintainable code
How to write maintainable codeHow to write maintainable code
How to write maintainable code
 
Script writing (2)
Script writing (2)Script writing (2)
Script writing (2)
 
A Pragmatic Approach
A Pragmatic ApproachA Pragmatic Approach
A Pragmatic Approach
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 
Est 102 ppt1
Est 102 ppt1Est 102 ppt1
Est 102 ppt1
 
Programming Languages
Programming LanguagesProgramming Languages
Programming Languages
 
TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...
TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...
TCUK 2013 - Mike Unwalla - Patterns in language for POS disambiguation in a s...
 
Py con 2012 my presentation
Py con 2012 my presentationPy con 2012 my presentation
Py con 2012 my presentation
 

Semelhante a What the math geeks don't want you to know about F#

Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#Alfonso Garcia-Caro
 
F# and functional programming
F# and functional programmingF# and functional programming
F# and functional programmingramikarjalainen
 
Bay NET Aug 19 2009 presentation ppt
Bay  NET Aug 19 2009 presentation pptBay  NET Aug 19 2009 presentation ppt
Bay NET Aug 19 2009 presentation pptArt Scott
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPtutorialsruby
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPtutorialsruby
 
Inheritance Versus Roles - The In-Depth Version
Inheritance Versus Roles - The In-Depth VersionInheritance Versus Roles - The In-Depth Version
Inheritance Versus Roles - The In-Depth VersionCurtis Poe
 
F# Sample and Resources
F# Sample and ResourcesF# Sample and Resources
F# Sample and ResourcesRhonda Tipton
 
Envisioning the Future of Language Workbenches
Envisioning the Future of Language WorkbenchesEnvisioning the Future of Language Workbenches
Envisioning the Future of Language WorkbenchesMarkus Voelter
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Ti1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming LinguisticsTi1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming LinguisticsEelco Visser
 
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...PROIDEA
 

Semelhante a What the math geeks don't want you to know about F# (20)

Practical F#
Practical F#Practical F#
Practical F#
 
Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#
 
F# and functional programming
F# and functional programmingF# and functional programming
F# and functional programming
 
Bay NET Aug 19 2009 presentation ppt
Bay  NET Aug 19 2009 presentation pptBay  NET Aug 19 2009 presentation ppt
Bay NET Aug 19 2009 presentation ppt
 
F# Tutorial @ QCon
F# Tutorial @ QConF# Tutorial @ QCon
F# Tutorial @ QCon
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
 
Inheritance Versus Roles - The In-Depth Version
Inheritance Versus Roles - The In-Depth VersionInheritance Versus Roles - The In-Depth Version
Inheritance Versus Roles - The In-Depth Version
 
F# Sample and Resources
F# Sample and ResourcesF# Sample and Resources
F# Sample and Resources
 
Envisioning the Future of Language Workbenches
Envisioning the Future of Language WorkbenchesEnvisioning the Future of Language Workbenches
Envisioning the Future of Language Workbenches
 
F# 101
F# 101F# 101
F# 101
 
Ruby
RubyRuby
Ruby
 
Introduction to F#
Introduction to F#Introduction to F#
Introduction to F#
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Ti1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming LinguisticsTi1220 Lecture 1: Programming Linguistics
Ti1220 Lecture 1: Programming Linguistics
 
Intro To AOP
Intro To AOPIntro To AOP
Intro To AOP
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 

Mais de Kevin Hazzard

C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIKevin Hazzard
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersKevin Hazzard
 
Better contracts better code - august 2010
Better contracts   better code - august 2010Better contracts   better code - august 2010
Better contracts better code - august 2010Kevin Hazzard
 
Introduction to SQL Azure
Introduction to SQL AzureIntroduction to SQL Azure
Introduction to SQL AzureKevin Hazzard
 
Enterprise Data Validation
Enterprise Data ValidationEnterprise Data Validation
Enterprise Data ValidationKevin Hazzard
 
Dynamic Language Performance
Dynamic Language PerformanceDynamic Language Performance
Dynamic Language PerformanceKevin Hazzard
 

Mais de Kevin Hazzard (7)

C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
 
Better contracts better code - august 2010
Better contracts   better code - august 2010Better contracts   better code - august 2010
Better contracts better code - august 2010
 
Introduction to SQL Azure
Introduction to SQL AzureIntroduction to SQL Azure
Introduction to SQL Azure
 
Enterprise Data Validation
Enterprise Data ValidationEnterprise Data Validation
Enterprise Data Validation
 
Dynamic Language Performance
Dynamic Language PerformanceDynamic Language Performance
Dynamic Language Performance
 

Último

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
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
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Último (20)

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
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
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
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
 

What the math geeks don't want you to know about F#

  • 1. What the Math Geeks Don't Want You to Know about F# Tips for OvercomingObstacles to Learning F# August 2010 Kevin Hazzard, C# MVP
  • 2. What This Talk Is & Is Not This talk does not intend to teach F# deeply This talk is for C# / VB.NET programmers trying to answer the questions: Why should I care about functional languages? What makes F# worth learning? What's going to slow me down on the journey?
  • 3. What makes a language functional? Compositional and often expression-oriented Supports functions as first-class types Often promotes lazy evaluation Extensive use of higher-order functions Avoids memory and I/O side-effects Prefers recursion over iteration Excellent for concurrent programming May have polymorphic data types withextensive pattern matching capabilities
  • 4. A Teaching Example type BinaryTree<'a> = | Leaf of 'a | Node of BinaryTree<'a> * BinaryTree<'a>
  • 5. Obstacle #1 Pattern matching is foreign and pervasive. Pattern matching is at the core of F# When learning F#, focus on every pattern matching example you can find Start with the simple ones, e.g. discriminated unions, move up and out Treat this learning as a block and learn it deeply, in a very focused way
  • 6. Obstacle #2 Type inference makes F# feel like a scripting language. If you're a Pythonista, you will feel at home writing F# - the types get out of your way If not… Watch carefully for inferred types, especially while you are learning – use the FSI REPL a lot Use automatic generalization to reduce code volume and increase simplicity
  • 7. Automatic Generalization No obstacle but something to be aware of What type does this operate on? let max a b = if a > b then a else b F# automatically generalizes complete expressions when it can
  • 8. Recursion – Port This to F# public inthcf( intx, inty ) { int result = 0; while (result == 0) { if (x < y) { y %= x; if (y == 0) result = x; } else { x %= y; if (x == 0) result = y; } } return result; }
  • 9. Isn't This Succinct? let rechcf a b =if a = 0 then belifb = 0 then aelif a < b then hcf a (b % a)else hcf (a % b) b
  • 10. Tail Recursion Optimization Recursive functions that do no extra work after the recursion can often be converted to while loops F# does this automatically if the code is structured to allow for it The JITter will sometimes do this on compiled code No guarantees though
  • 11. Obstacle #3 Recursion may be at odds with your belief system. Many of us were taught to fear recursion Stop thinking that way Every time you write an iteration think,"Could this be done with recursion instead?" Write your F# code so that it is tail optimizable
  • 12. Workflows (Computation Expressions) Bind Delay Return ReturnFrom Combine For TryFinally TryWith Using While YieldFrom Zero
  • 13. Obstacle #4 Workflows are central to F# and tough to understand. Think of workflows like little Domain Specific Languages (DSL) Builders are like AOP-enabled classes, allowing you to hook and define those 12 core functions When the F# code in the computation expression is evaluated, your code gets to direct the work Focus on understanding the built-in async workflow
  • 14. VS Gallery F# Templates When you first look at the F# templates in VS 2010, you may be underwhelmed The F# team and others are always adding F# templates to ease development Daniel Mohl (@dmohl) has written some excellent templates that are available in the online gallery
  • 15. Obstacle #5 You must rewire your brain a bit to learn F#. F# is part of the .NET ecosystem Great tooling in Visual Studio 2010 Full access to all .NET types and members Seamless access to & from C# and VB.NET F# is multi-paradigm Emphasizes data immutability and the evaluation of expressions But also supports traditional OOP concepts
  • 16. Don't Get Hung Up On Terms Lambda Calculus Turing Completeness Universal Computer Endofunctors Cata/Ana-morphism Co-algebras Category Theory "How does this help me to write better software?"
  • 17. Stuff That Is Important Composition / Currying Pattern Matching Type inference Immutability Side-effects Recursion Workflows
  • 18. Obstacle #6 Functional programming is a new fad. It will pass. Anyone want to guess how long functional programming has been around? OOP dominated because it was the best way to reduce complexity and promote reuse in CPU-bound systems Functional languages are leader languages Data structures Message and event passing Dynamic typing and type inferencing Generics Garbage collection
  • 19. The History of F# Started in 2002 in Microsoft Research Based on languages like ML and OCaml Influenced great stuff in .NET Generics LINQ Visual Studio support in versions 2005 & 2008 Became a first-class language citizen inVisual Studio 2010
  • 20. Demo Check out the F# Samplescode.msdn.microsoft.com/fsharpsamples Explore Tutorial.fs with Alt + Enter Samples101

Notas do Editor

  1. This talk is not about teaching the F# language. We&apos;ll look at some code, for sure. This talk is for devs who know C# or VB.NET and looking at typical F# makes you say, &quot;Huh?&quot; I&apos;ll highlight some key concepts and tell you about stuff that will trip you up. In that context, we&apos;ll also talk about how you can approach the language in a much more manageable way, leveraging the skills you already have.
  2. Functional languages tend to be a lot more succinct or terse than their imperative counterparts. F# is both functional and object-oriented. But the syntax is close to its functional cousins like OCaml and Haskell that are very terse. In those languages, like F#, you tend to be able to express a lot of intent with very little code. There&apos;s a tipping point, of course, where languages become so terse, so compact that the lose the ability to convey meaningful information to human readers. F# strikes a nice balance but it can be overwhelming to read if you&apos;re accustomed to languages like C#, much more so VB.NET which is praised for its &quot;wordiness&quot; by those who love it.The central theme to functional languages is, of course, functions. They are first class citizens. Declaring a lambda expression is easy using the fun keyword. But standalone functions can be declared in such a way that they can be connected together, or composed using a concept called currying. When I first began working with functional languages, I thought that currying had something to do with the spicy curries used in Indian and Asian foods. These are sauces made up of a lot of varying spices. I mistakenly thought that currying in functional programming got its name from mixing lots of functions together to get a result. I was naïve. We all are at some point in learning new things. Currying in functional programming gets its name from Haskell Curry, a major name in computer science whose first name is also lent to the purely functional programming language called Haskell.Currying (and composition of functions in general) are very important concepts in FP languages. Being able to pass functions to other functions and lazily evaluate results only when they are needed, immutability is possible. And when you can have truly immutable data structures, you can make the leap to expression-orientation, where you tell the compiler what you want to accomplish, not exactly how to do it. When the compiler and runtime tooling can look at an expression abstractly and farm varying parts off to different processors, you begin to take advantage of the so-called multi-core revolution that&apos;s under way right now. Writing multi-threaded code is hard. Even the best of us, who&apos;ve been writing symmetric multi-processing (SMP) code for decades can make serious but subtle mistakes trying to farm out a complex operation to all of the available CPUs.Multi-processing is not the only reason to code functionally. Functional software is easier to test in many cases. If you think about it, how many of your unit tests are designed to test capabilities to mutating object state? Yeah, a lot of them.
  3. A discriminated union that can contain a leaf node or another binary tree. Great for building binary trees of data. Notice how terse the syntax is. It might read, here&apos;s a binary tree of some unknown type. It can contain either a Leaf of that unknown type or another binary tree called Node. (create the type in FSI and talk about the output here) Now let&apos;s write a function to print out a tree:let recprintBinaryTreeValuest = match t with | Leaf x -&gt; printfn &quot;%i&quot; x | Node (l, r) -&gt;printBinaryTreeValueslprintBinaryTreeValuesrNotice the rec keyword? That means recursive. In F#, you must mark recursive functions as such. We use the let keyword to assign symbols to things. The printBinaryTree symbol is assigned to the code below it. F# is whitespace sensitive like other languages I love, e.g. Python. I think it makes the code so much more readable to get rid of all the curly braces and the BEGIN/END type keywords. The parameter to this method is also declared without a lot of decoration. That symbol is &quot;t&quot;. The equals sign after that separates the symbol assignment from the code. The code starts with a pattern match. It says to match the parameter t to either a Leaf or a Node from our BinaryTree type. When it&apos;s a Leaf, just print out the value there. When it&apos;s a Node, recurse twice to visit the left and right trees there instead. There&apos;s no return type from this function which is why the output type is listed as &quot;unit&quot;. Now let&apos;s create a binary tree and run this depth-first visitor to print it out:printBinaryTreeValues (Node ((Node (Leaf 1, Leaf 2)), (Node (Leaf 3, Leaf 4))))Cool. Here&apos;s a slightly more interesting function that will visit each node and print out the data with more detail and indentation:let printBinaryTreet = let recprintBinaryTreet indent = match t with | Leaf x -&gt; printfn &quot;%sLeaf %i&quot; indent x | Node (l, r) -&gt;printfn &quot;%sLeft Branch&quot; indentprintBinaryTreel (indent + &quot; &quot;)printfn &quot;%sRight Branch&quot; indentprintBinaryTreer (indent + &quot; &quot;)printBinaryTreet &quot;&quot;Notice that this function called printBinaryTree has another function defined within it. The inner function is limited in scope, of course. And using the same name for the inner function is OK because the signatures are different. See how the inner function takes 2 parameters while the outer one only takes one parameter? The inner function uses that new parameter to say how far to indent information that&apos;s printed out depending on how deep the traversal is in the tree. Run this with the same tree we used before:printBinaryTree (Node ((Node (Leaf 1, Leaf 2)), (Node (Leaf 3, Leaf 4))))Nice. Now, since the BinaryTree is generic, should we able pass tree of string nodes to it? Let&apos;s try this:printBinaryTree (Node ((Node (Leaf &quot;Kevin&quot;, Leaf &quot;Donna&quot;)), (Node (Leaf &quot;Ted&quot;, Leaf &quot;Charlotte&quot;))))That didn&apos;t work. Why? The error message says something about expecting integers when we gave it strings. Go back and look at the response that FSI gave us when we created this new function. It says:valprintBinaryTree : BinaryTree&lt;int&gt; -&gt; unitThat&apos;s odd. Nowhere in the definition of this function did I say that the type of the binary tree was integers did I? Look closely. Buried in the printfn statement for the Leaf type is &quot;%i&quot; which tells F# to interpret the parameter as an integer. This is an example of how deep F#&apos;s type inference engine goes. Change that %i formatter and replace it with %O which tells F# that it&apos;s an object we’re passing and that it should box values as necessary and invoke ToString() on them. Save the new function into the REPL. What does it say is the type?valprintBinaryTree : BinaryTree&lt;&apos;a&gt; -&gt; unitAhhh! Much better. Now retry the sample data with strings in the nodes to see if it works. It does! Hooray!
  4. Here are some examples:let biggestFloat = max 3.0 3.1415927let biggestInt = max 7 2let biggestString = max &quot;Kevin&quot; &quot;Donna&quot;
  5. Some ancient code to find the highest common factor written in C#:public inthcf( intx, inty ){int result = 0; while (result == 0) { if (x &lt; y) {y %= x; if (y == 0) result = x; } else {x %= y; if (x == 0) result = y; } } return result;}// porting the iterative code directly to F# - yuck!let hcf a b = let mutable x = a let mutable y = b let mutable result = 0 while result = 0 do if x &lt; y theny &lt;- y % x if y = 0 then result &lt;- x elsex &lt;- x % y if x = 0 then result &lt;- y result// try this call – hcf should be 12hcf 29292 4524That&apos;s some ugly F# - mutation is a warning sign. If you have to mark something mutable, you are most likely writing bad F#. There are cases where you may be working with third party libraries that depend on mutation. And it&apos;s OK to do it then, of course. But for your code, always try to avoid data mutation. If you need to change data, copy it, changing what you need and pass that to a function. This is much better:let rechcf a b = if a = 0 then belifb = 0 then aelif a &lt; b then hcf a (b % a) else hcf (a % b) bFor fun, try this:hcf 17350618 26025927Jenny&apos;s phone number is, in fact, a prime number. 
  6. Read this: Successively reduce the lesser parameter to the integer remainder of division with the greater parameter until one reaches zero. So much more readable than the iterative version. And recursion is the more natural way to express this idea.
  7. A workflow builder is like an AOP-hookable class. You inject methods for implementing these 12 methods, as many or as few as you need to handle flow constructs and bindings. In this simple example, we&apos;ll create a TraceBuilder that simply traces the Bind, Delay and Result events during the workflow execution.Define 3 functions for Bind, Result and Delay:let bind value1 function1 = printfn &quot;Binding %A.&quot; value1 function1 value1let result value1 =printfn &quot;Returning result: %A&quot; value1 fun () -&gt; value1let delay function1 = fun () -&gt; function1()Now tie those implementations into the TraceBuilder class by name:type TraceBuilder() = member x.Bind(value1, function1) = bind value1 function1 member x.Return(value1) = result value1 member x.Delay(function1) = printfn &quot;Starting traced execution.&quot; delay function1Instantiate the builder:let trace = new TraceBuilder()Bind it to the expression code:let trace1 = trace { let x = 7 let! y = 5 let sum = x + y return sum }And execute:let output = trace1()A great way to learn the usefulness of workflows is by studying one of the built in workflows called async:open System.Netopen System.Threadingopen Microsoft.FSharp.Control.WebExtensionslet fetchAsync(name, url:string) =async { try let uri = new System.Uri(url) let webClient = new WebClient() let! html = webClient.AsyncDownloadString(uri)printfn &quot;Thread %i: Read %d characters for %s&quot; Thread.CurrentThread.ManagedThreadIdhtml.Length name with | ex -&gt; printfn &quot;%s&quot; (ex.Message); }let urlList = [ &quot;Kevin&apos;s Blog&quot;, &quot;http://devjourney.com&quot; &quot;MSDN&quot;, &quot;http://msdn.microsoft.com&quot; &quot;Bing&quot;, &quot;http://www.bing.com&quot; ]let runAll() =urlList |&gt; Seq.mapfetchAsync |&gt; Async.Parallel |&gt; Async.RunSynchronously |&gt; ignorerunAll()
  8. Open Visual Studio and select the online templates when creating a new project. Filter to F# and examine the available templates.
  9. When someone gives an FP talk and they day catamorphism, please raise you hand and say, &quot;Isn&apos;t a catamorphism just a fold operation on a sequence?&quot; If they say, &quot;Well… yeah.&quot; Then ask, &quot;Why can&apos;t you just say fold? Why do you have to use mathematics terms to explain something so simple to us?&quot; Speakers in the FP world need to learn to speak to us on our terms and in the language that we understand.Anamorphism = unfold