## Tuesday, 31. January 2012

Jan 31

This is yet another blog post in my Currying and Partial application series. This is what I have posted so far:

In this post I want to show you a way to simulate type classes in C# and F#. Type classes are this wonderful feature in Haskell which allow you to specify constraints on your polymorphic types. We donâ€™t have this in C# nor F#.

Letâ€™s start with the following problem: We want to compute the sum of the squares of arbitrary numbers. We want to write something like this:

The problem is we donâ€™t have a generic * function and of course weâ€™d also need a generic + operator and maybe a generic zero. Obviously we need a constraint on the generic parameter T since + might not be defined for any type. So letâ€™s define an interface for numbers:

Nothing special here, so let’s get straight to the implementation for integers and doubles:

So far so good. With this in our pocket we rewrite SumOfSquares() into this:

The trick is that we pass the concrete implementation as the first parameter into our function. This works exactly like a type constraint or as Simon Peyton-Jones would say: the vtable travels into the function. Notice that we donâ€™t have access to the definition of in nor double. There is no way for us to express that int or double implement a number interface.

Now letâ€™s try this out:

As you can see, this is perfectly type safe. We now have a way for poor manâ€™s type classes in C#. Yay!

Now what has this to do with partial application? Letâ€™s look at the same thing in F#:

We’re using a lot of partial application here. Exercise: Try to spot all the places.

Ok, youâ€™re right. This post might be a little bit far away from the partial application stuff, but itâ€™s still related. Somehow.

Tags:

C-Sharp,

Currying,

F#,

partial application,

type classes
## Monday, 30. January 2012

Jan 30

In the last couple of days I started to write some posts about Currying and Partial application:

This time I want to show you how we can write a higher-order function which allows us to curry another function. Remember the multiplication function from the first post and itâ€™s curried form:

##### Currying

The question is: how can we automate this transformation process? Remember we want to have the curryied form for partial application:

Letâ€™s look at the signature of the desired Curry-function: in our case it has to take **Func<int, int, int>** and returns **Func<int, Func<int, int>>**.

If we generalize the **ints** to generic parameters and fix the signature then the implementation is trivial (Compiler Driven Programming). There is exactly one way to make this work:

The F# implementation does exactly the same, but without all the annoying the type hints:

##### Uncurrying

Of course you can undo the currying by applying a generic Uncurry-function:

And in F# this looks like this:

##### Libraries

Currying and Uncurrying are two very important concepts in functional programming so they are included in a couple of libraries:

- You can find it at the top of the Prelude in FSharpx (read more).
- You can find it in the Haskell Prelude.
- You can find similar functions in Scalaz.
- Adrian Lang wrote a library called partial-js which allows to do something similar in JavaScript.

Tags:

C-Sharp,

Currying,

F#,

partial application
## Sunday, 29. January 2012

Jan 29

My last blog post was yet another introduction to Currying and Partial application. Now I want to put the focus more on the **why** part. Why do we want to have our functions in curryied form most of the time? This is the first part of a small blog post series and shows partial application in F# pipelines.

Using â€œFluent interfacesâ€ is a popular technique to write code in a more readable form. In languages like C# they also provide a way to create the code much faster. On every . we get IntelliSense and this gives us a â€œfluidâ€ way of writing.

Letâ€™s consider the following task: we want to compute the sum of the square roots of all odd numbers between 1 and 100. In C# we can use the LINQ method chaining approach in order to do something like this:

Now how does this look in F#? Itâ€™s basically the same. We replace every . with the |> operator and use the analogous Seq.* functions:

Oups! What happened here? The F# compiler noticed a type error. **Math.Sqrt** needs a float as input but we gave it an int. C# uses implicit casts between int and float so we didnâ€™t noticed the problem there. Implicit casts are a little bit problematic, at least if you want to have proper type inference so F# doesnâ€™t have this feature. No problem, we are programmers so letâ€™s add the conversion manually:

Notice that **float** is a function from int to float and not a cast.

Now you might ask: how does this all relate to partial application? The answer is simple: In every pipeline step we use a higher-order function (Seq.*) and apply the first parameter with a lambda. The second parameter is given via the |> operator from the line above.

By applying our rule of thumb from the last post were are able to remove the x parameters:

Now letâ€™s step back to C#. Keeping this knowledge in mind we try to apply the same rule in order to get rid of the x parameters:

Oups again! Now we see same error in C#. In this case it doesnâ€™t know how to apply the implicit cast. As I said they are â€œproblematicâ€, but we know how to fix this:

Tags:

Currying,

F#,

partial application
## Friday, 27. January 2012

Jan 27

Today I had a conversation on twitter about partial application and type inference in F#. Partial application is a very important and useful concept and there are a lot of resources out there. Here is a short list of related material:

I promised to show a small sample and I hope this clarifies some of my points on twitter. Let’s consider a multiplication function in C#:

This function allows us to compute the product of two ints. But what can I do when I need a function which doubles its input? The solutions is easy: I just create a new function:

And when I need a function which triples its input? Same thing, just create another method. But can we do better?

Letâ€™s transform the multiplication function into the curryied version. The transformation process is very easy once you see the pattern. Itâ€™s actually possible to write a function which curryies another function, but thatâ€™s something for another post. Anyway, hereâ€™s the curryied version:

It’s a little bit noisy with all the funky Funcs, but Ok. We can still write the double function in terms of multiply:

And of course we can use multiply directly (which might look a bit weird at first):

But we can also use it in another way, which we couldn’t really do before:

How cool is this? We just applied a single parameter and we got a new function without writing any method declarations. Unfortunately we wrote a lot of weird type declarations in order to get here, but hey.

Letâ€™s move to a language which has type inference. Hereâ€™s the uncurryied version of multiply in F#:

The type signature tells us, that we have to give it a tuple of ints and then we get an int back. Thatâ€™s exactly the same as in C#. Notice that we think about x1,x2 as only one parameter â€“ a tuple. How can we get to the curryied form? It couldnâ€™t be easier: just remove the parentheses and youâ€™re done:

As you can see the type signature changes a little bit. The * is now just another arrow. This means we have basically the same as Func<int, Func<int, int>> but in a much nicer syntax. There is also another way to write this:

This looks like the C# version, but notice how nicely the arrows align to the type signature. If we want to use the multiply function than we can write something like this:

Itâ€™s also very easy to create partially applied functions:

And finally the point which made me write this post. There is a simple rule: whenever we have the same parameter as the last parameter of the left and the right side of a function definition, we can remove it. This leads us to:

Isn’t this beautiful?

Tags:

Currying,

F#,

partial application
## Wednesday, 17. June 2009

Jun 17

Yesterday I was talking about F# at the .NET Developer Group Braunschweig. It was my first talk completely without PowerPoint (just Live-Coding and FlipChart) and I have to admit this is not that easy. But the event was really a big fun and we covered a lot of topics like FP fundamentals, concurrency and domain specific languages (of course I showed â€œFAKE â€“ F# Makeâ€).

Now I have a bit time before I go to the next BootCamp in Leipzig. Today Christian Weyer will show us exciting new stuff about WCF and Azure.

In the meanwhile I will write here about another important question (see first article) from the F# BootCamp in Leipzig:

##### Question 4 â€“ Try to explain â€œCurryingâ€ and â€œPartial Applicationâ€. Hint: Please show a sample and use the pipe operator |>.

Obviously this was a tricky question for FP beginners. There are a lot of websites, which give a formal mathematical definition but donâ€™t show the practical application.

â€œCurrying â€¦ is the technique of transforming a function that takes multiple arguments (or more accurately an n-tuple as argument) in such a way that it can be called as a chain of functions each with a single argumentâ€

[Wikipedia]

I want to show how my pragmatic view of the terms here, so letâ€™s consider this small C# function:

public int Add(int x, int y)
{
return x + y;
}

Of course the corresponding F# version looks nearly the same:

let add(x,y) = x + y

But letâ€™s look at the signature: *val add : int*** *** int â€“> int. The F# compiler is telling us **add **wants a tuple of ints and returns an int. We could rewrite the function with one blank to understand this better:

let add (x,y) = x + y

As you can see the add function actually needs only one argument â€“ a tuple:

let t = (3,4) // val t : int * int
printfn "%d" (add t) // prints 7 â€“ like add(3,4)

Now we want to curry this function. If youâ€™d ask a mathematician this a complex operation, but from a pragmatic view it couldnâ€™t be easier. Just remove the brackets and the comma â€“ thatâ€™s all:

let add x y = x + y

Now the signature looks different: *val add : int*** ->** int â€“> int

But whatâ€™s the meaning of this new arrow? Basically we can say if we give one int parameter to our add function we will get a function back that will take only one int parameter and returns an int.

let increment = add 1 // val increment : (int -> int)
printfn "%d" (increment 2) // prints 3

Here â€œincrementâ€ is a new function that uses partial application of the curryied add function. This means we are fixing one of the parameters of **add **to get a new function with one parameter less.

But why are doing something like this? Wouldnâ€™t it be enough to use the following increment function?

let add(x,y) = x + y // val add : int * int -> int
let increment x = add(x,1) // val increment : int -> int
printfn "%d" (increment 2) // prints 3

Of course we are getting (nearly) the same signature for increment. But the difference is that we can not use the forward pipe operator **|>** here. The pipe operator will help us to express things in the way we are thinking about it.

Letâ€™s say we want to filter all even elements in a list, then calculate the sum and finally square this sum and print it to the console. The C# code would look like this:

var list = new List<int> {4,2,6,5,9,3,8,1,3,0};
Console.WriteLine(Square(CalculateSum(FilterEven(list))));

If we donâ€™t want to store intermediate results we have to write our algorithm in reverse order and with heavily use of brackets. The function we want to apply last has to be written first. This is not the way we think about it.

With the help of curried functions, partial application and the pipe operator we can write the same thing in F#:

let list = [4; 2; 6; 5; 9; 3; 8; 1; 3; 0]
let square x = x * x

list
|> List.filter (fun x -> x % 2 = 0) // partial application
|> List.sum
|> square
|> printfn "%A" // partial application

We describe the data flow in exactly the same order we talked about it. Basically the pipe operator take the result of a function and puts it as the **last** parameter into the next function.

What should we learn from this sample?

- Currying has nothing to do with spicy chicken.
- The |> operator makes life easier and code better to understand.
- If we want to use |> we need curryied functions.
- Defining curryied functions is easy â€“ just remove brackets and comma.
- We donâ€™t need the complete mathematical theory to use currying.
- Be careful with the order of the parameter in a curryied function. Donâ€™t forget the pipe operator puts the parameter from the right hand side into your function â€“ all other parameters have to be fixed with partial application.

Tags:

.NET Developer Group Braunschweig,

.NET User Group Leipzig,

Currying,

F#,

F-sharp Make,

Fake,

partial application,

pipe,

|>