Thursday, May 15, 2014

Partial apply in C#

Partial apply by Wikipedia:

In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function \scriptstyle f \colon (X \times Y \times Z) \to N , we might fix (or 'bind') the first argument, producing a function of type  \scriptstyle\text{partial}(f) \colon (Y \times Z) \to N . Evaluation of this function might be represented as f_{partial}(2, 3). Note that the result of partial function application in this case is a function that takes two arguments.

In short, that means you define (bind) some of the possible arguments and leave some to be filled in later (free).


def sum(a:Int, b:Int, c:Int):Int = a+b+c  //> sum: (a: Int, b: Int, c: Int)Int
sum(1,2,3)                                //> res11: Int = 6

def sum1 = sum(1, _:Int, _:Int)           //> sum1: => (Int, Int) => Int
sum1(2,3)                                 //> res12: Int = 6

def sum2 = sum(_:Int, 2, _:Int)           //> sum2: => (Int, Int) => Int
sum2(1,3)                                 //> res13: Int = 6

sum1 binds the first parameter but the other two parameters are free. As you can see from the result it gets translated to a lambda with two parameters.

sum2 binds the second parameter. The result is the same, a lambda with two parameters.


C# has no built-in operator for applying a function, so we have to write the lambdas directly.

readonly Func sum = (x, y, z) => x + y + z;

public void Sum()
    var result = sum(1, 2, 3);

    Assert.Equal(6, result);

public void Sum_PartialApply_FirstParam()
    Func sum1 = (y, z) => sum(1, y, z);

    var result = sum1(2, 3);

    Assert.Equal(6, result);

public void Sum_PartialApply_SecondParam()
    Func sum2 = (x, z) => sum(x, 2, z);

    var result = sum2(1, 3);

    Assert.Equal(6, result);

Wednesday, May 14, 2014

Loan pattern in C#

There is a pattern is Scala called loan pattern. You open a resource, “loan” the resource to another function, and the loaner closes the resource.


This function expects a file a function. When it's called it creates the resource, executes the function and closes the resource.

def withPrintWriter(file: File, op: PrintWriter => Unit) {
  val writer = new PrintWriter(file)
  try {
  } finally {

This is how it's called:

  new File("date.txt"),
  writer => writer.println(new java.util.Date)


Now I extended the definition with currying:

readonly Func, string>> openFile = 
    path => 
        handler =>
                var reader = new StreamReader(path);
                    return handler(reader);
                    Console.WriteLine("Stream closed");

Here are two examples on calling the function above:

readonly Func readAllLines = input => input.ReadToEnd();
readonly Func readSingleLine = input => input.ReadLine();

public void LoanPattern_AllText()
    var result = openFile("TextFile1.txt")(readAllLines);
    Assert.Equal("This is the test content.\r\nThis is a second line.", result);

public void LoanPattern_ReadSingleLine()
    var result = openFile("TextFile1.txt")(readSingleLine);
    Assert.Equal("This is the test content.", result);


Now the code calling the function (openFile) is much simpler and there is no need for error handling in the caller. Furthermore thanks to currying, even the resource name can be bound in the constructor, hiding the resource initialization as well.

Thursday, May 8, 2014

Currying in Scala and C#

Currying is an interesting and powerful functional programming concept. Interestingly currying can be used in C# as well.

The usual approach

Let's define a simple add function that sums two numbers in C#:

public void SimpleAdd_AsInlineFunction_WithLambda()
    Func<int, int, int> add = (x, y) => x + y;
    var result = add(5, 7);
    Assert.Equal(12, result);

The same in Scala:

def add(x:Int,y:Int) = x+y                      //> add: (x: Int, y: Int)Int
add(5,7)                                        //> res0: Int = 12
Or with lambda:
def add_lambda = (x:Int,y:Int) => x+y           //> add_lambda: => (Int, Int) => Int
add_lambda(5,7)                                 //> res1: Int = 12


Now Implement the same function in C#, but this time with currying:

public void CurryingAdd()
    Func<int, Func<int, int>> add = x => y => x + y;
    var result = add(5)(7);
    Assert.Equal(12, result);

In Scala:

def add_lambda_currying(x:Int) = (y:Int) => x+y //> add_lambda_currying: (x: Int)Int => Int
add_lambda_currying(5)(7)                       //> res2: Int = 12

With simplified Scala syntax:

def add_currying(x:Int)(y:Int): Int = x+y       //> add_currying: (x: Int)(y: Int)Int
add_currying(5)(7)                              //> res3: Int = 12

Partial apply

Now let’s suppose I want to bind the first parameter to a concrete value (bound) but I want to keep the second parameter unbounded (free).

This is the way in C#:

public void CurryingAdd_Add5()
    Func> add = x => y => x + y;
    var add5 = add(5);
    var result1 = add5(7);
    Assert.Equal(12, result1);

    var result2 = add5(122);
    Assert.Equal(127, result2);

The same idea in Scala:

def add5_lambda_currying = add_lambda_currying(5)  //> add5_lambda_currying: => Int => Int
add5_lambda_currying(7)                         //> res3: Int = 12

def add5_currying = add_currying(5) _           //> add5_currying: => Int => Int
add5_currying(7)                                //> res5: Int = 12

In case of the add5_currying example please notice the underscore (_) at the end of the expression. That means partial apply and indicates that I don’t want to bind the second parameter. There is no need for such indicator with lambda syntax.

Friday, February 7, 2014

Functional C# - insight by Python

Python has many powerful functions. I realized there are many similar functions available in .NET.

Function Description .NET
zip Pairs iterables element by element:

* x = [1, 2, 3]
* y = [4, 5, 6]
* zipped = zip(x, y)
* zipped
[(1, 4), (2, 5), (3, 6)]


int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = 
    numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)

// 1 one 
// 2 two 
// 3 three

reduce Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words. 
string[] words = sentence.Split(' ');

// Prepend each word to the beginning of the  
// new sentence to reverse the word order. 
string reversed = words.Aggregate((workingSentence, next) =>
                                                  next + " " + workingSentence);

// dog lazy the over jumps fox brown quick the 
filterConstruct a list from those elements of iterable for which function returns true.

filter(lambda x: x%2, range(10)) 
result: 1 3 5 7 9
List fruits =
new List { "apple", "passionfruit", "banana", "mango", 
    "orange", "blueberry", "grape", "strawberry" };

IEnumerable query = fruits.Where(fruit => fruit.Length < 6);

This code produces the following output: