SlideShare a Scribd company logo
1 of 34
Functional patterns and
techniques in C#
Péter Takács
Senior Software Engineer @ LogMeIn
peter.takacs@windowslive.com
2017
Developers love FP
http://stackoverflow.com/insights/survey/2016#technology-most-loved-dreaded-and-wanted
F# in production
http://fsharp.org/testimonials/#handelsbanken-1
What is functional programming?
„In computer science, functional programming is
a programming paradigm—a style of building the structure and
elements of computer programs—that treats computation as
the evaluation of mathematical functions and avoids changing-
state and mutable data. It is a declarative
programming paradigm, which means programming is done
with expressions or declarations instead of statements.”
https://en.wikipedia.org/wiki/Functional_programming
Mathematical (pure) functions
„In mathematics, a function is a relation between a set of
inputs and a set of permissible outputs with the property
that each input is related to exactly one output.”
FunctionInput Output
https://en.wikipedia.org/wiki/Function_(mathematics)
public TimeSpan GetAge(DateTime birthdate)
{
return DateTime.Now – birthdate;
}
Not a mathematical function
public TimeSpan GetAge(
DateTime birthdate,
DateTime now)
{
return now – birthdate;
}

public float Divide(int a, int b)
{
return a / b;
}
Not a mathematical function
public float Divide(int a, NonZeroInt b)
{
return a / b;
}

public Option<float> Divide(int a, int b)
{
if(b == 0)
return new Option();
else
return new Option(a / b);
}

public void SaveUser(string email, string name)
{
if(email == null)
throw new ArgumentNullException(”email”)
if(EmailValidator.IsValid(email))
throw new InvalidEmailException(email);
…
}
Not a mathematical function
Primitive Obsession
public void SaveUser(Email email, string name)
{
if(email == null)
throw new ArgumentNullException(”email”)
…
}
Not a mathematical function
public void SaveUser(Email email, string name)
{
if(email == null)
throw new ArgumentNullException(”email”)
…
} „My billion-dollar mistake” …
„simply because it was so
easy to implement”
Tony Hoare
https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/
public void SaveUser(
[NotNull] Email email,
[NotNull] string name)
{ ReSharper Code Annotations
Not a mathematical function
public Either<Unit, Error> SaveUser(
Email email,
string name)
{
…
return new Either<Error>(Error.AlreadyExists);
…
return new Either<Unit>();
}
≈void
svc.SaveUser(new Email(”some@email.hu”), ”Peter”)
.Match(
result => Console.WriteLine(”OK”),
error => this.logger.Log(error));
Poor man’s pattern matching
Frist-class citizen function
(delegates)
Higher-order function
Mathematical (pure) functions
• Easy to reason about it (side-effect free)
• Composable
• Testable
• Scalable
Making invalid states
unrepresentable
https://fsharpforfunandprofit.com/posts/designing-with-types-making-illegal-states-unrepresentable/
Imperative vs
Declarative
var user = userRepository.Get(userId);
if (user?.Document != null)
{
var document = documentRepository.Get(user.Document.Id);
if (document?.LastModiferUser != null)
{
var lastModifier =
userRepository.Get(document.LastModiferUser.Id);
return lastModifier;
}
}
return null;
Option<User> lastModifier =
this.userRepository.Get(userId)
.Bind(r => r.Document)
.Bind(r => documentRepository.Get(d.Id))
.Bind(r => r.LastModifier)
.Bind(r => userRepository.Get(u.Id))
https://github.com/louthy/language-ext
class Person
{
public string Name { get; }
public Person(string name) =>
Name = name ??
throw new ArgumentNullException(name);
public string GetLastName() =>
throw new NotImplementedException();
}
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
class Person
{
private static ConcurrentDictionary<int, string> names =
new ConcurrentDictionary<int, string>();
public Person(string name) => names.TryAdd(id, name);
~Person() => names.TryRemove(id, out *);
public string Name
{
get => names[id];
set => names[id] = value;
}
}
https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
public static Task<int> PerformWorkAsync(int value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("…");
if (value > 100)
throw new ArgumentOutOfRangeException("…");
async Task<int> AsyncPart()
{
await Task.Delay(value * 500);
return value * 500;
}
return AsyncPart();
}
http://thebillwagner.com/Blog/Item/2016-03-02-C7FeatureProposalLocalFunctions
Local functions
Currying, partial application
Currying is the technique of translating the evaluation of a function that takes
multiple arguments into evaluating a sequence of functions, each with a single
argument.
public void Log(
string module,
string category,
Level level,
string message)
{
…
}
var logger =
LogMethod("web")("user");
logger(Level.High)("msg1");
logger(Level.Low)("msg2");
https://en.wikipedia.org/wiki/Currying
Action<string, string, Level, string> log = Log;
Action<string, Action<string, Action<Level, Action<string>>>>
curriedLog = Curry(log);
var logger = curriedLog("web")("user");
var curriedLog = Curry(log);
var logger = curriedLog("web")("user");
logger(Level.High)("msg1");
// curry vs partial application
partialLogger = ApplyPartial<string, string, Level, string>(
log, "web", "user");
partialLogger(Level.High, "msg1");
Func<T1, Func<T2, Func<T3, TResult>>> Curry<T1, T2, T3, TResult>
(Func<T1, T2, T3, TResult> function)
{
return a => b => c => function(a, b, c);
}
https://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/
Tuples (and C# 7)
• When you want to return multiple values, and you don’t
want to create a class for that
Tuple<int, int> t1 = Tuple.Create<int, int>(1, 2);
int value = t1.Item1 + t1.Item2;
Tuples (and C# 7)
• When you want to return multiple values, and you don’t
want to create a class for that
private static (int Max, int Min) Range(List<int> numbers)
{
…
return (Max, Min)
}
Immutability
• const
• readonly
• IReadOnlyCollection<T> and
System.Collections.Immutable (Array, Dictionary,
List …)
Key takeaways
• Use pure functions wherever you can
• Write side-effect free code
• Prefer immutable structures over mutable
• Type signature as documentation
(avoid Primitive Obession)
• Learn functional programming 
Start learning functional programming!
Contact me if you have any questions
peter.takacs@windowslive.com
https://www.linkedin.com/in/petertakacs1

More Related Content

What's hot

Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
Hipster oriented programming (Mobilization Lodz 2015)
Hipster oriented programming (Mobilization Lodz 2015)Hipster oriented programming (Mobilization Lodz 2015)
Hipster oriented programming (Mobilization Lodz 2015)Jens Ravens
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
Hipster Oriented Programming
Hipster Oriented ProgrammingHipster Oriented Programming
Hipster Oriented ProgrammingJens Ravens
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaDamian Jureczko
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftColin Eberhardt
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in PracticeOutware Mobile
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java langer4711
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project LambdaRahman USTA
 
Learn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great GoodLearn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great GoodJason Larsen
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language EnhancementsYuriy Bondaruk
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second sessionJean Marcel Belmont
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in JavaErhan Bagdemir
 
Developing R Graphical User Interfaces
Developing R Graphical User InterfacesDeveloping R Graphical User Interfaces
Developing R Graphical User InterfacesSetia Pramana
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Fwdays
 

What's hot (20)

Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
 
Hipster oriented programming (Mobilization Lodz 2015)
Hipster oriented programming (Mobilization Lodz 2015)Hipster oriented programming (Mobilization Lodz 2015)
Hipster oriented programming (Mobilization Lodz 2015)
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Hipster Oriented Programming
Hipster Oriented ProgrammingHipster Oriented Programming
Hipster Oriented Programming
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 
ReactiveCocoa in Practice
ReactiveCocoa in PracticeReactiveCocoa in Practice
ReactiveCocoa in Practice
 
Gpars workshop
Gpars workshopGpars workshop
Gpars workshop
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Learn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great GoodLearn You a ReactiveCocoa for Great Good
Learn You a ReactiveCocoa for Great Good
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second session
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Developing R Graphical User Interfaces
Developing R Graphical User InterfacesDeveloping R Graphical User Interfaces
Developing R Graphical User Interfaces
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"
 

Similar to Functional patterns and techniques in C#

Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureJayaram Sankaranarayanan
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fpAlexander Granin
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaMartijn Blankestijn
 
Spark what's new what's coming
Spark what's new what's comingSpark what's new what's coming
Spark what's new what's comingDatabricks
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented ProgrammingAndrey Bratukhin
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35Bilal Ahmed
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32Bilal Ahmed
 
Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Soham Kulkarni
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceDatabricks
 
Scala.js for large and complex frontend apps
Scala.js for large and complex frontend appsScala.js for large and complex frontend apps
Scala.js for large and complex frontend appsOtto Chrons
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsBizTalk360
 

Similar to Functional patterns and techniques in C# (20)

Rx workshop
Rx workshopRx workshop
Rx workshop
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Spark what's new what's coming
Spark what's new what's comingSpark what's new what's coming
Spark what's new what's coming
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Aspect-Oriented Programming
Aspect-Oriented ProgrammingAspect-Oriented Programming
Aspect-Oriented Programming
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32
 
Compiler Construction for DLX Processor
Compiler Construction for DLX Processor Compiler Construction for DLX Processor
Compiler Construction for DLX Processor
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
Scala.js for large and complex frontend apps
Scala.js for large and complex frontend appsScala.js for large and complex frontend apps
Scala.js for large and complex frontend apps
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Functional patterns and techniques in C#

  • 1. Functional patterns and techniques in C# Péter Takács Senior Software Engineer @ LogMeIn peter.takacs@windowslive.com 2017
  • 4. What is functional programming? „In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing- state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations instead of statements.” https://en.wikipedia.org/wiki/Functional_programming
  • 5. Mathematical (pure) functions „In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output.” FunctionInput Output https://en.wikipedia.org/wiki/Function_(mathematics)
  • 6. public TimeSpan GetAge(DateTime birthdate) { return DateTime.Now – birthdate; } Not a mathematical function
  • 7. public TimeSpan GetAge( DateTime birthdate, DateTime now) { return now – birthdate; } 
  • 8. public float Divide(int a, int b) { return a / b; } Not a mathematical function
  • 9. public float Divide(int a, NonZeroInt b) { return a / b; } 
  • 10. public Option<float> Divide(int a, int b) { if(b == 0) return new Option(); else return new Option(a / b); } 
  • 11. public void SaveUser(string email, string name) { if(email == null) throw new ArgumentNullException(”email”) if(EmailValidator.IsValid(email)) throw new InvalidEmailException(email); … } Not a mathematical function Primitive Obsession
  • 12. public void SaveUser(Email email, string name) { if(email == null) throw new ArgumentNullException(”email”) … } Not a mathematical function
  • 13. public void SaveUser(Email email, string name) { if(email == null) throw new ArgumentNullException(”email”) … } „My billion-dollar mistake” … „simply because it was so easy to implement” Tony Hoare https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/
  • 14. public void SaveUser( [NotNull] Email email, [NotNull] string name) { ReSharper Code Annotations Not a mathematical function
  • 15. public Either<Unit, Error> SaveUser( Email email, string name) { … return new Either<Error>(Error.AlreadyExists); … return new Either<Unit>(); } ≈void
  • 16. svc.SaveUser(new Email(”some@email.hu”), ”Peter”) .Match( result => Console.WriteLine(”OK”), error => this.logger.Log(error)); Poor man’s pattern matching Frist-class citizen function (delegates) Higher-order function
  • 17. Mathematical (pure) functions • Easy to reason about it (side-effect free) • Composable • Testable • Scalable
  • 20. var user = userRepository.Get(userId); if (user?.Document != null) { var document = documentRepository.Get(user.Document.Id); if (document?.LastModiferUser != null) { var lastModifier = userRepository.Get(document.LastModiferUser.Id); return lastModifier; } } return null;
  • 21. Option<User> lastModifier = this.userRepository.Get(userId) .Bind(r => r.Document) .Bind(r => documentRepository.Get(d.Id)) .Bind(r => r.LastModifier) .Bind(r => userRepository.Get(u.Id)) https://github.com/louthy/language-ext
  • 22.
  • 23. class Person { public string Name { get; } public Person(string name) => Name = name ?? throw new ArgumentNullException(name); public string GetLastName() => throw new NotImplementedException(); } https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
  • 24. class Person { private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>(); public Person(string name) => names.TryAdd(id, name); ~Person() => names.TryRemove(id, out *); public string Name { get => names[id]; set => names[id] = value; } } https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
  • 25. public static Task<int> PerformWorkAsync(int value) { if (value < 0) throw new ArgumentOutOfRangeException("…"); if (value > 100) throw new ArgumentOutOfRangeException("…"); async Task<int> AsyncPart() { await Task.Delay(value * 500); return value * 500; } return AsyncPart(); } http://thebillwagner.com/Blog/Item/2016-03-02-C7FeatureProposalLocalFunctions Local functions
  • 26. Currying, partial application Currying is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. public void Log( string module, string category, Level level, string message) { … } var logger = LogMethod("web")("user"); logger(Level.High)("msg1"); logger(Level.Low)("msg2"); https://en.wikipedia.org/wiki/Currying
  • 27. Action<string, string, Level, string> log = Log; Action<string, Action<string, Action<Level, Action<string>>>> curriedLog = Curry(log); var logger = curriedLog("web")("user");
  • 28. var curriedLog = Curry(log); var logger = curriedLog("web")("user"); logger(Level.High)("msg1"); // curry vs partial application partialLogger = ApplyPartial<string, string, Level, string>( log, "web", "user"); partialLogger(Level.High, "msg1");
  • 29. Func<T1, Func<T2, Func<T3, TResult>>> Curry<T1, T2, T3, TResult> (Func<T1, T2, T3, TResult> function) { return a => b => c => function(a, b, c); } https://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application/
  • 30. Tuples (and C# 7) • When you want to return multiple values, and you don’t want to create a class for that Tuple<int, int> t1 = Tuple.Create<int, int>(1, 2); int value = t1.Item1 + t1.Item2;
  • 31. Tuples (and C# 7) • When you want to return multiple values, and you don’t want to create a class for that private static (int Max, int Min) Range(List<int> numbers) { … return (Max, Min) }
  • 32. Immutability • const • readonly • IReadOnlyCollection<T> and System.Collections.Immutable (Array, Dictionary, List …)
  • 33. Key takeaways • Use pure functions wherever you can • Write side-effect free code • Prefer immutable structures over mutable • Type signature as documentation (avoid Primitive Obession) • Learn functional programming 
  • 34. Start learning functional programming! Contact me if you have any questions peter.takacs@windowslive.com https://www.linkedin.com/in/petertakacs1

Editor's Notes

  1. https://www.infoq.com/news/2016/05/csharp7-pattern-matching-removed