SlideShare une entreprise Scribd logo
1  sur  150
Applying functional
programming approaches in
object oriented languages
Mark Needham
© ThoughtWorks 2010
C# 1.0
int[] ints = new int[] {1, 2, 3, 4, 5}
int[] Filter(int[] ints)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (i % 2 == 0)
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
int[] ints = new int[] {1, 2, 3, 4, 5}
int[] Filter(int[] ints)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (i > 3 == 0)
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
int[] Filter(int[] ints)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (i % 2 == 0)
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
int[] Filter(int[] ints)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (i >3 == 0)
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
interface IIntegerPredicate
{
bool Matches(int value);
}
class EvenPredicate : IIntegerPredicate
{
bool Matches(int value)
{
return value % 2 == 0;
}
}
class GreaterThan3Predicate : IIntegerPredicate
{
bool Matches(int value)
{
return value > 3;
}
}
int[] Filter(int[] ints, IIntegerPredicate predicate)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (predicate.Matches(i))
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
int[] ints = new int[] {1, 2, 3, 4, 5 };
int[] even = Filter(ints, new EvenPredicate());
int[] greaterThan3 = Filter(ints, new GreaterThan3Predicate());
interface IIntegerPredicate
{
bool Matches(int value);
}
bool delegate IntegerPredicate(int value);
bool Even(int value)
{
return value % 2 == 0;
}
bool GreaterThan3(int value)
{
return value > 3;
}
int[] Filter(int[] ints, IntegerPredicate predicate)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (predicate(i))
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
int[] ints = new int[] {1, 2, 3, 4, 5 };
int[] even = Filter(ints, new IntegerPredicate(Even));
int[] greaterThan3 = Filter(ints,
new IntegerPredicate(GreaterThan3));
C# 2.0
Inference
int[] ints = new int[] {1, 2, 3, 4, 5 };
int[] even = Filter(ints, new IntegerPredicate(Even));
int[] greaterThan3 = Filter(ints,
new IntegerPredicate(GreaterThan3));
Inference
int[] ints = new int[] {1, 2, 3, 4, 5 };
int[] even = Filter(ints, Even);
int[] greaterThan3 = Filter(ints, GreaterThan3);
Generics
delegate bool IntegerPredicate(int value);
Generics
delegate bool Predicate<T> (T value);
Generics
int[] Filter(int[] ints, IntegerPredicate predicate)
{
ArrayList results = new ArrayList();
foreach (int i in ints)
{
if (predicate(i))
{
results.Add(i);
}
}
return results.ToArray(typeof(int));
}
Generics
T[] Filter<T>(T[] values, Predicate<T> predicate)
{
List<T> results = new List<T>();
foreach (T i in value)
{
if (predicate(i))
{
results.Add(i);
}
}
return results.ToArray();
}
Iterators
IEnumerable<T> Filter<T>(IEnumerable<T> values,
Predicate<T> p)
{
List<T> results = new List<T>();
foreach (T i in value)
{
if (p(i))
{
results.Add(i);
}
}
return results;
}
Iterators
IEnumerable<T> Filter<T>(IEnumerable<T> values,
Predicate<T> p)
{
foreach (T i in value)
{
if (p(i))
{
yield return i;
}
}
}
Anonymous Methods
IEnumerable<int> greaterThan3 = Filter(ints, GreaterThan3);
Anonymous Methods
IEnumerable<int> greaterThan3 = Filter(ints,
delegate(int value) { return value > 3; });
Anonymous Methods
int minimumValue = 3;
IEnumerable<int> greaterThan3 = Filter(ints,
delegate(int value) { return value > minimumValue; });
C# 3.0
Lambdas
int minimumValue = 3;
IEnumerable<int> greaterThan3 = Filter(ints,
delegate(int value) { return value > minimumValue; });
Lambdas
int minimumValue = 3;
IEnumerable<int> greaterThan3 = Filter(ints,
value => value > minimumValue);
More Type Inference
int minimumValue = 3;
IEnumerable<int> greaterThan3 = Filter(ints,
value => value > minimumValue);
More Type Inference
int minimumValue = 3;
var greaterThan3 = Filter(ints, value => value > minimumValue);
Extension Methods
int minimumValue = 3;
var greaterThan3 = Filter(ints, value => value > minimumValue);
Extension Methods
int minimumValue = 3;
var greaterThan3 = ints.Filter(value => value > minimumValue);
LINQ
LINQ
New delegates in System namespace
Action<T>, Action<T1, T2>, Func<TResult>, Func<T1, TResult>
etc.
LINQ
New delegates in System namespace
Action<T>, Action<T1, T2>, Func<TResult>, Func<T1, TResult>
etc.
System.Linq
Extension methods Where, Select, OrderBy etc.
LINQ
New delegates in System namespace
Action<T>, Action<T1, T2>, Func<TResult>, Func<T1, TResult>
etc.
System.Linq
Extension methods Where, Select, OrderBy etc.
Some compiler magic to translate sql style code to method calls
LINQ
var even = ints.Where(value => value % 2 == 0)
var greaterThan3 = ints.Where(value => value > 3)
or
var even = from value in ints
where value % 2 == 0
select value
var greaterThan3 = from value in ints
where value > 3
select value
Interfaces
Delegates
Anonymous methods
Lambdas
So this functional programming thing…
http://www.flickr.com/photos/stuartpilbrow/2938100285/sizes/l/
Higher order functions
var ints = new int[] {1, 2, 3, 4, 5 };
var greaterThan3 = ints.Where(value => value > 3)
var even = ints.Where(value => value % 2 == 0)
Pure functions
Immutability
Lazy evaluation
Iterators
IEnumerable<T> Filter<T>(IEnumerable<T> values,
Predicate<T> p)
{
foreach (T i in value)
{
if (p(i))
{
yield return i;
}
}
}
Recursion & Pattern Matching
Transformational Mindset
We can just pass functions around instead in most cases
- find an example where it still makes sense to use the GOF approach
though.
Input -> ??? -> ??? -> ??? -> Output
http://www.emt-india.net/process/petrochemical/img/pp4.jpg
So why should you care?
Functional can fill in the gaps in OO code
Programming in the…
Large
Medium
Small
Programming in the …
Large
Medium
Small
“a high level that affects as well as crosscuts multiple
classes and functions”
Programming in the …
Large
Medium
Small
“a single API or group of related APIs in such things
as classes, interfaces, modules”
Programming in the …
Large
Medium
Small
“individual function/method bodies”
Large
Medium
Small
Large
Medium
Small
Abstractions over common operations means less
code and less chances to make mistakes
Projection
people.Select(person => person.Name)
people.SelectMany(person => person.Pets)
Restriction
people.Where(person => person.HasPets)
Partitioning
people.Take(5)
people.Skip(5)
people.TakeWhile(person =>
person.Name != "David")
people.SkipWhile(person =>
person.Name != "David")
Set
people.Select(person => person.Name)
.Distinct()
people.Union(someOtherPeople)
people.Intersect(someOtherPeople)
people.Except(someOtherPeople)
Ordering and Grouping
people.OrderBy(person => person.Name)
people.GroupBy(person => person.Name)
Aggregation
people.Count()
people.Select(person => person.Age)
.Sum()
people.Select(person => person.Age)
.Min()
people.Select(person => person.Age)
.Max()
people.Select(person => person.Age)
.Average()
people.Select(person => person.Age)
.Aggregate(0, (totalAge, nextAge) =>
nextAge % 2 == 0
? nextAge + totalAge
: totalAge)
Joining
people.Join(addresses,
person => person.PersonId,
address => address.PersonId,
(person, address) => new {
person, address})
Embrace the collection
var first = “Mark”;
var middle = “Harold”;
var surname = “Needham”;
var fullname = first + “ “ + middle + “ “ + surname;
or
var names = new[] {first, middle, surname};
var fullname = String.Join(“ “, names);
public class SomeObject
{
public SomeObject(string p1, string p2, string p3)
{
if(p1 == null)
throw new Exception(…);
if(p2 == null)
throw new Exception(…);
if(p3 == null)
throw new Exception(…);
// rest of constructor logic
}
}
public class SomeObject
{
public SomeObject(string p1, string p2, string p3)
{
var parameters = new[] {p1, p2, p3};
if(parameters.Any(p => p = null)
throw new Exception(…).
// rest of constructor logic
}
}
Large
Medium
Small
We can just pass functions around instead in most cases
- find an example where it still makes sense to use the GOF approach
though.
public class SomeObject
{
private readonly IStrategy strategy;
public SomeObject(IStrategy strategy)
{
this.strategy = strategy;
}
public void DoSomething(string value)
{
strategy.DoSomething(value);
}
}
public class Strategy : IStrategy
{
public void DoSomething(string value)
{
// do something with string
}
}
public class SomeObject
{
private readonly Action<string> strategy;
public SomeObject(Action<string> strategy)
{
this.strategy = strategy;
}
public void DoSomething(string value)
{
strategy(value);
}
}
Hole in the middle pattern
public class ServiceCache<Service>
{
protected Res FromCacheOrService
<Req, Res>(Func<Res> serviceCall, Req request)
{
var cachedRes = cache.RetrieveIfExists(
typeof(Service), typeof(Res), request);
if(cachedRes == null)
{
cachedRes = serviceCall();
cache.Add(typeof(Service), request, cachedRes);
}
return (Res) cachedRes;
}
}
public class CachedService : ServiceCache<IService>
{
public MyResult GetMyResult(MyRequest request)
{
return FromCacheOrService(()
=> service.GetMyResult(request), request);
}
}
Maybe?
public interface Maybe<T>
{
bool HasValue();
T Value();
}
public class Some<T> : Maybe<T>
{
private readonly T theThing;
public Some(T theThing)
{
this.theThing = theThing;
}
public bool HasValue ()
{
return true;
}
public T Value()
{
return theThing;
}
}
public class None<T> : Maybe<T>
{
public bool HasValue ()
{
return false;
}
public T Value()
{
throw new NotImplementedException();
}
}
public class Some
{
public static Some<T> Thing<T>(T thing)
: where T : class
{
return new Some<T>(thing);
}
}
public class No
{
public static None<T> Thing<T>()
{
return new None<T>();
}
}
public static class MaybeExtensions
{
public static Maybe<T> Maybify<T>(this T source)
where T : class
{
if(source == null)
return No.Thing<T>();
return Some.Thing(source);
}
}
recordFromDatabase.Maybify():
public class FooService
{
public Foo FindOrCreate(int fooId)
{
var foo = fooRepository.Find(fooId);
if(foo.HasValue())
{
return foo.Value();
}
return fooRepository.Create(fooId);
}
}
Continuation Passing Style
static void Identity<T>(T value, Action<T> k)
{
k(value);
}
Identity("foo", s => Console.WriteLine(s));
Identity("foo", s => Console.WriteLine(s));
as compared to
var foo = Identity(“foo”);
Console.WriteLine(foo);
public ActionResult Submit(string id, FormCollection form) {
var shoppingBasket = CreateShoppingBasketFrom(id, form);
return IsValid(shoppingBasket, ModelState,
() => RedirectToAction("index", "ShoppingBasket", new { shoppingBasket.Id} ),
() => LoginUser(shoppingBasket,
() =>
{
ModelState.AddModelError("Password", "User name/email address was
incorrect - please re-enter");
return RedirectToAction("index", ""ShoppingBasket",
new { Id = new Guid(id) });
},
user =>
{
shoppingBasket.User = user;
UpdateShoppingBasket(shoppingBasket);
return RedirectToAction("index", "Purchase",
new { Id = shoppingBasket.Id });
}
));
}
private RedirectToRouteResult IsValid(ShoppingBasket
shoppingBasket,
ModelStateDictionary modelState,
Func<RedirectToRouteResult> failureFn,
Func<RedirectToRouteResult> successFn)
{
return validator.IsValid(shoppingBasket, modelState) ? successFn() : failureFn();
}
private RedirectToRouteResult LoginUser(ShoppingBasket
shoppingBasket,
Func<RedirectToRouteResult> failureFn,
Func<User,RedirectToRouteResult> successFn)
{
User user = null;
try
{
user = userService.CreateAccountOrLogIn(shoppingBasket);
}
catch (NoAccountException)
{
return failureFn();
}
return successFn(user);
}
Passing functions around
private void AddErrorIf<T>(Expression<Func<T>> fn,
ModelStateDictionary modelState,
Func<ModelStateDictionary,
Func<T,string, string, bool>> checkFn)
{
var fieldName = ((MemberExpression)fn.Body).Member.Name;
var value = fn.Compile().Invoke();
var validationMessage = validationMessages[fieldName]);
checkFn.Invoke(modelState)(value, fieldName, validationMessage);
}
AddErrorIf(() =>
person.HasPets, modelState,
m => (v, f, e) => m.AddErrorIfNotEqualTo(v,true, f, e));
AddErrorIf(() =>
person.HasChildren, modelState,
m => (v, f, e) => m.AddErrorIfNull(v, f, e));
http://www.thegeekshowpodcast.com/home/mastashake/thegeekshowpodcast.com/wp-content/uploads/2009/07/wtf-cat.jpg
So what could possibly go wrong?
http://icanhascheezburger.files.wordpress.com/2009/06/funny-pictures-cat-does-not-think-plan-will-fail.jpg
Hard to diagnose errors
var people = new []
{
new Person { Id=1, Address =
new Address { Road = "Ewloe Road" }},
new Person { Id=2},
new Person { Id=3, Address =
new Address { Road = "London Road"}}
};
people.Select(p => p.Address.Road);
Null Reference Exception on line 23
http://www.flickr.com/photos/29599641@N04/3147972713/
public T Tap(T t, Action action)
{
action();
return t;
}
people
.Select(p => Tap(p, logger.debug(p.Id))
.Select(p => p.Address.Road);
if we have side effects then favour foreach construct
foreach(var item in items)
{
itemRepository.Save(item);
}
rather than:
items.ToList().ForEach(item => itemRepository.Save(item));
Readability
Lazy evaluation can have unexpected
consequences
IEnumerable<string> ReadNamesFromFile()
{
using(var fileStream = new FileStream("names.txt",
FileMode.Open))
using(var reader = new StreamReader(fileStream))
{
var nextLine = reader.ReadLine();
while(nextLine != null)
{
yield return nextLine;
nextLine = reader.ReadLine();
}
}
}
IEnumerable<Person> GetPeople()
{
return ReadNamesFromFile()
.Select(name => new Person(name));
}
IEnumerable<Person> people = GetPeople();
foreach (var person in people)
{
Console.WriteLine(person.Name);
}
Console.WriteLine("Total number of people: " +
people.Count());
Encapsulation is still important
public Money CalculateSomething(Func<Customer,
DateTime, Money> calculation)
{
// do some calculation
}
public delegate Money PremiumCalculation(Customer
customer, DateTime renewalDate);
public Money CalculateSomething(
PremiumCalculation calculation)
{
// do some calculation
}
Total salary for a company
company.Employees
.Select(employee => employee.Salary)
.Sum()
This could lead to duplication
What if we add rules to the calculation?
Who should really have this responsibility?
.Sum()
Linq isn't the problem here, it's where we
have put it
Company naturally has the responsibility so
encapsulate the logic here
class Company
{
public int TotalSalary
{
get
{
return employees.Select(e =>e.Salary).Sum();
}
}
}
Sometimes we need to go further
If both Company and Division have employees do
we duplicate the logic for total salary?
IEnumerable<T> and List<T> make collections
easy but sometimes it is still better to create a
class to represent a collection
class EmployeeCollection
{
private List<Employee> employees;
public int TotalSalary
{
get
{
return employees.Select(e => e.Salary).Sum();
}
}
}
In conclusion…
Mark Needham
mneedham@thoughtworks.com
© ThoughtWorks 2010

Contenu connexe

Tendances

CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Codemotion
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingEelco Visser
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
 

Tendances (20)

Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
Composing method
Composing methodComposing method
Composing method
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Pointer
PointerPointer
Pointer
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
Trie Data Structure
Trie Data StructureTrie Data Structure
Trie Data Structure
 
Numerical analysisgroup19
Numerical analysisgroup19Numerical analysisgroup19
Numerical analysisgroup19
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Trie Data Structure
Trie Data StructureTrie Data Structure
Trie Data Structure
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 

Similaire à Applying functional programming approaches in object oriented languages

Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Skills Matter
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersTikal Knowledge
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
The Arrow Library in Kotlin
The Arrow Library in KotlinThe Arrow Library in Kotlin
The Arrow Library in KotlinGarth Gilmour
 
Kotlin for Android Developers - 2
Kotlin for Android Developers - 2Kotlin for Android Developers - 2
Kotlin for Android Developers - 2Mohamed Nabil, MSc.
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useSharon Rozinsky
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...tdc-globalcode
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1H K
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Codemotion
 

Similaire à Applying functional programming approaches in object oriented languages (20)

Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
JBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java ProgrammersJBUG 11 - Scala For Java Programmers
JBUG 11 - Scala For Java Programmers
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
The Arrow Library in Kotlin
The Arrow Library in KotlinThe Arrow Library in Kotlin
The Arrow Library in Kotlin
 
Kotlin for Android Developers - 2
Kotlin for Android Developers - 2Kotlin for Android Developers - 2
Kotlin for Android Developers - 2
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 

Plus de Mark Needham

Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsMark Needham
 
This week in Neo4j - 3rd February 2018
This week in Neo4j - 3rd February 2018This week in Neo4j - 3rd February 2018
This week in Neo4j - 3rd February 2018Mark Needham
 
Building a recommendation engine with python and neo4j
Building a recommendation engine with python and neo4jBuilding a recommendation engine with python and neo4j
Building a recommendation engine with python and neo4jMark Needham
 
Graph Connect: Tuning Cypher
Graph Connect: Tuning CypherGraph Connect: Tuning Cypher
Graph Connect: Tuning CypherMark Needham
 
Graph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easilyGraph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easilyMark Needham
 
Graph Connect Europe: From Zero To Import
Graph Connect Europe: From Zero To ImportGraph Connect Europe: From Zero To Import
Graph Connect Europe: From Zero To ImportMark Needham
 
Optimizing cypher queries in neo4j
Optimizing cypher queries in neo4jOptimizing cypher queries in neo4j
Optimizing cypher queries in neo4jMark Needham
 
Football graph - Neo4j and the Premier League
Football graph - Neo4j and the Premier LeagueFootball graph - Neo4j and the Premier League
Football graph - Neo4j and the Premier LeagueMark Needham
 
The Football Graph - Neo4j and the Premier League
The Football Graph - Neo4j and the Premier LeagueThe Football Graph - Neo4j and the Premier League
The Football Graph - Neo4j and the Premier LeagueMark Needham
 
Scala: An experience report
Scala: An experience reportScala: An experience report
Scala: An experience reportMark Needham
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
F#: What I've learnt so far
F#: What I've learnt so farF#: What I've learnt so far
F#: What I've learnt so farMark Needham
 

Plus de Mark Needham (13)

Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and OperationsNeo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
Neo4j GraphTour: Utilizing Powerful Extensions for Analytics and Operations
 
This week in Neo4j - 3rd February 2018
This week in Neo4j - 3rd February 2018This week in Neo4j - 3rd February 2018
This week in Neo4j - 3rd February 2018
 
Building a recommendation engine with python and neo4j
Building a recommendation engine with python and neo4jBuilding a recommendation engine with python and neo4j
Building a recommendation engine with python and neo4j
 
Graph Connect: Tuning Cypher
Graph Connect: Tuning CypherGraph Connect: Tuning Cypher
Graph Connect: Tuning Cypher
 
Graph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easilyGraph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easily
 
Graph Connect Europe: From Zero To Import
Graph Connect Europe: From Zero To ImportGraph Connect Europe: From Zero To Import
Graph Connect Europe: From Zero To Import
 
Optimizing cypher queries in neo4j
Optimizing cypher queries in neo4jOptimizing cypher queries in neo4j
Optimizing cypher queries in neo4j
 
Football graph - Neo4j and the Premier League
Football graph - Neo4j and the Premier LeagueFootball graph - Neo4j and the Premier League
Football graph - Neo4j and the Premier League
 
The Football Graph - Neo4j and the Premier League
The Football Graph - Neo4j and the Premier LeagueThe Football Graph - Neo4j and the Premier League
The Football Graph - Neo4j and the Premier League
 
Scala: An experience report
Scala: An experience reportScala: An experience report
Scala: An experience report
 
Visualisations
VisualisationsVisualisations
Visualisations
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
F#: What I've learnt so far
F#: What I've learnt so farF#: What I've learnt so far
F#: What I've learnt so far
 

Dernier

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Dernier (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Applying functional programming approaches in object oriented languages

Notes de l'éditeur

  1. So now we can change that function to read like this
  2. origins of functional programming are found in lambda calculation/maths
  3. origins of functional programming are found in lambda calculation/maths
  4. functions that take in a function or return a function. Need to have first class functions in the language to do that. We have that with all the LINQ methods - select, where, and so on.
  5. side effect free functions - input and output. ‘Nothing’ else should be affected We can't achieve this idiomatically in C# because the language isn't really designed for it. in this section?
  6. the whole premise of functional programming with side effect free functions assumes that we have immutable data. We can't achieve this idiomatically in C# because the language isn't really designed for it. I want to put an example of how immutability is easy in F#, can that go in this section?
  7. iterators in C# do this with yield keyword It's not necessary to have lazy evaluation to be functional but it's a characteristic of some functional languages.
  8. seems quite obvious but the most extreme guideline to follow is that we shouldn't need to store anything in variables. Look at the data as a whole if we don't store any intermediate values then we truly do have some data that we are passing through different filters and applying some transformation
  9. it's quite like the pipes and filters architectural pattern in fact. This is the way that we can combine functions on the unix command line.
  10. what is CPS?   is where we pass in a function that represents the rest of the program which will be called with the result of another function.
  11. A version of the maybe monad
  12. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  13. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  14. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  15. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  16. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  17. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  18. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  19. what is CPS?   is where we pass in a function that represents the rest of the program which will be called with the result of another function.
  20. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  21. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  22. the idea is that the rest of the program is contained in the continuation so we don't need to come back to the call site.
  23. Encapsulates the state but over complicates the program flow perhaps
  24. what is CPS?   is where we pass in a function that represents the rest of the program which will be called with the result of another function.
  25. Encapsulates the state but over complicates the program flow perhaps
  26. Name the delegates if they’re used all over the place