SlideShare a Scribd company logo
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
Functional patterns and techniques in C#
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 (20)

ODP
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
PDF
Intake 37 linq2
Mahmoud Ouf
 
PDF
Hipster oriented programming (Mobilization Lodz 2015)
Jens Ravens
 
ODP
Concurrency on the JVM
Vaclav Pech
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
Hipster Oriented Programming
Jens Ravens
 
PDF
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
PDF
Reactive cocoa made Simple with Swift
Colin Eberhardt
 
PDF
ReactiveCocoa in Practice
Outware Mobile
 
PDF
Gpars workshop
Vaclav Pech
 
PDF
Programming with Lambda Expressions in Java
langer4711
 
PPT
Java 8 Streams
Manvendra Singh
 
PDF
Java 8 - Project Lambda
Rahman USTA
 
PDF
Learn You a ReactiveCocoa for Great Good
Jason Larsen
 
PDF
Java8: Language Enhancements
Yuriy Bondaruk
 
PPTX
Code craftsmanship saturdays second session
Jean Marcel Belmont
 
PPT
Create and analyse programs
Dr. C.V. Suresh Babu
 
PDF
Lambda Expressions in Java
Erhan Bagdemir
 
PPTX
Developing R Graphical User Interfaces
Setia Pramana
 
PDF
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Fwdays
 
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Intake 37 linq2
Mahmoud Ouf
 
Hipster oriented programming (Mobilization Lodz 2015)
Jens Ravens
 
Concurrency on the JVM
Vaclav Pech
 
Java 8 Lambda Expressions
Scott Leberknight
 
Hipster Oriented Programming
Jens Ravens
 
Teach Yourself some Functional Programming with Scala
Damian Jureczko
 
Reactive cocoa made Simple with Swift
Colin Eberhardt
 
ReactiveCocoa in Practice
Outware Mobile
 
Gpars workshop
Vaclav Pech
 
Programming with Lambda Expressions in Java
langer4711
 
Java 8 Streams
Manvendra Singh
 
Java 8 - Project Lambda
Rahman USTA
 
Learn You a ReactiveCocoa for Great Good
Jason Larsen
 
Java8: Language Enhancements
Yuriy Bondaruk
 
Code craftsmanship saturdays second session
Jean Marcel Belmont
 
Create and analyse programs
Dr. C.V. Suresh Babu
 
Lambda Expressions in Java
Erhan Bagdemir
 
Developing R Graphical User Interfaces
Setia Pramana
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Fwdays
 

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

PPTX
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
PPTX
Leveraging benefits of the functional paradigm
Afif Mohammed
 
PDF
Functional Programming in C#
Giorgio Zoppi
 
PPTX
Mixing functional programming approaches in an object oriented language
Mark Needham
 
PDF
Pragmatic functional refactoring with java 8 (1)
RichardWarburton
 
PDF
The Functional Programming Toolkit (NDC Oslo 2019)
Scott Wlaschin
 
PDF
Pragmatic functional refactoring with java 8
RichardWarburton
 
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PDF
Pragmatic Functional Refactoring with Java 8
Codemotion
 
ODP
Functional programming
S M Asaduzzaman
 
PPTX
Functional Programming with C#
EastBanc Tachnologies
 
PDF
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
PPTX
Functional programming
PiumiPerera7
 
PPTX
How Functional Programming Made Me A Better Developer
Cameron Presley
 
PDF
379008-rc217-functionalprogramming
Luis Atencio
 
PDF
Functional Principles for OO Developers
jessitron
 
PDF
Introduction to functional programming
Thang Mai
 
PPTX
Functional Programming
Ryan Riley
 
PPTX
Thinking Functionally with JavaScript
Luis Atencio
 
PPTX
Why functional programming in C# & F#
Riccardo Terrell
 
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
Leveraging benefits of the functional paradigm
Afif Mohammed
 
Functional Programming in C#
Giorgio Zoppi
 
Mixing functional programming approaches in an object oriented language
Mark Needham
 
Pragmatic functional refactoring with java 8 (1)
RichardWarburton
 
The Functional Programming Toolkit (NDC Oslo 2019)
Scott Wlaschin
 
Pragmatic functional refactoring with java 8
RichardWarburton
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Pragmatic Functional Refactoring with Java 8
Codemotion
 
Functional programming
S M Asaduzzaman
 
Functional Programming with C#
EastBanc Tachnologies
 
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Functional programming
PiumiPerera7
 
How Functional Programming Made Me A Better Developer
Cameron Presley
 
379008-rc217-functionalprogramming
Luis Atencio
 
Functional Principles for OO Developers
jessitron
 
Introduction to functional programming
Thang Mai
 
Functional Programming
Ryan Riley
 
Thinking Functionally with JavaScript
Luis Atencio
 
Why functional programming in C# & F#
Riccardo Terrell
 
Ad

Recently uploaded (20)

PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
Ampere Offers Energy-Efficient Future For AI And Cloud
ShapeBlue
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
Apache CloudStack 201: Let's Design & Build an IaaS Cloud
ShapeBlue
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Top Managed Service Providers in Los Angeles
Captain IT
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
Ampere Offers Energy-Efficient Future For AI And Cloud
ShapeBlue
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
Apache CloudStack 201: Let's Design & Build an IaaS Cloud
ShapeBlue
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Ad

Functional patterns and techniques in C#

  • 1. Functional patterns and techniques in C# Péter Takács Senior Software Engineer @ LogMeIn [email protected] 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(”[email protected]”), ”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
  • 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 [email protected] https://www.linkedin.com/in/petertakacs1

Editor's Notes

  • #17: https://www.infoq.com/news/2016/05/csharp7-pattern-matching-removed