C# - Raise the bar with functional & immutable constructs (Dutch)

Post on 25-Jul-2015

433 views 2 download

Tags:

Transcript of C# - Raise the bar with functional & immutable constructs (Dutch)

C#Raise the bar with Functional & Immutable constructs

O, Kan dat ook?

Today• Func is cool• Tuple is your friend• Immutable is a life saver• Practice makes perfect• Action!

Actionpublic delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);

Funcpublic delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);

Tuplepublic class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, Ituple

Tuple: Equality

Functions• Data in – Data out• Func in – Data out• Data in – Func out• Func in – Func out

Functions: Data in – Data outx => 2 * x

Functions: Func in – Data out• LINQ: Where + more• Example: Object initialize• GitHub: https://

github.com/NForza/Functional/tree/master/Samples/ObjectInitialization

• Example: Aggregate• GitHub:

https://github.com/NForza/Functional/tree/master/Samples/Aggregate

Functions: Data in – Func outx => y => x + y

Functions: Func in – Func out• Example: Partial application• Example: Memoize

Partial Applicationvar f = (x, y) => x + y;var p = x => y => f(x, y);

Memoization• Pure functions• Long running operations

Memoization CacheNow:• Unlimited size, unlimited time

Ideas:• Limited size, unlimited time• Unlimited size, limited time• Don’t use the cache unless real

function takes > 1 sec.

Abstractions• 1 or n• for

• Is Index needed?• Is List/IList the correct abstraction (do we

need to change the list?)

• foreach• What & How are together• I hear functional abstraction

• Return: IEnumerable, IDictionary, IGroup

Immutable: Why?• Easier reasoning• Equality Has Meaning

(not in .NET’s immutable colleactions)• Sharing = Easy, no defensive copying

required!No ToArray() / ToList()• Concurrent Programming: No locks!

Immutable?• Int• String• Tuple• IEnumerable• IReadOnlyCollection/List/Dictionary• IList

Immutable Collections• ImmutableList<T>• ImmutableDictionary<TKey, TValue>• ImmutableSortedDictionary<TKey,

TValue>• ImmutableHashSet<T>• ImmutableSortedSet<T>• ImmutableStack<T>• ImmutableQueue<T>

Immutable Coll.: Performance

  Mutable (amortized)

Mutable(worst case)

Immutable

Stack.Push O(1) O(n) O(1)

Queue.Enqueue O(1) O(n) O(1)

List.Add O(1) O(n) O(log n)

HashSet.Add O(1) O(n) O(log n)

SortedSet.Add O(log n) O(n) O(log n)

Dictionary.Add O(1) O(n) O(log n)

SortedDictionary.Add O(log n) O(n log n) O(log n)

Immutable Coll.: Memory• Worse: Per Item• Better: No reserved space• Better: Immediate shrink after delete

Why?• Less code• Reusable• More fun!

Rick Beerendonkrick@nforza.nltwitter.com/rickbeerendonk

Simple. Clear. Software.