05 functional programming

Post on 10-May-2015

1.395 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Functional Programming Ideas in C#

What’s wrong with imperative code?

What’s wrong with imperative code?

What’s wrong with imperative code?

What’s wrong with imperative code?

• It is repetitive• It is lengthy• (higher chances to introduce bugs)• (harder to read)• It describes what to do and how• (mixing low-level and high-level

concepts)

Let’s try to solve these problems

Delegate declaration

Invocation

Invocation (without noise)

Delegates are immutable

You can only change the delegate variable

Delegate knows its target

Look, we manipulate code

as if it was data!

Nothing new though(we had interfaces for

ages)

So we can • Store it in variable• Store it in a field or property• Pass it as a method parameter• Return it as a method result

Functions (delegates) are first class citizens

Both pure and impure

Pure vs side-effects

• Pure functions:–Maht.Sin(X)– String.Length– List<T>.IndexOf(T)

• Functions with side effects:– List<T>.Add(T)– DateTime.UtcNow– Console.WriteLine()

Questions so far?

Consider the problem

• Initiate processing• When some condition occurs, we

want to execute some code

Pass delegates

Call event

Event syntax

Nothing really complicated so far

Let’s go deeper

Separate method -- not needed

Lambda expressions(lambda functions)

Return value from delegate

Let’s recall generics!

Questions so far?

How to make it more flexible?

This is called closure (lexical closure)

The function captures variables from the scope

Prefix

Pitfall

Function can even capture itself

Function factory

Generate IDs

We’ve looked at examples of

higher-order functions

Theytake one or more functions as an input

or return a function

Be comfortable with creating and passing lambdas

Understand closures

This is very powerful and widely used idiom

Let’s improve imperative code

Find element

Find element

Filter

Filter

Currying

Haskell Curry

Transform f: (X * Y) -> Z

into f: X -> (Y -> Z)

Input: Function with N parameters

Output: chain of N functions with 1 parameter each

Currying

How to compute Fibonacci(N)

What’s wrong with this?

It is exponential(slow)

link

Memoization

Memoization

Main ideas

• Functions as first class citizens• Compose complex functions from

simple• Create specific functions out of

generic ones• More generic and reusable code with

higher order functions• For less code and less bugs

Questions?

top related