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).

Scala

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#

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;

[Fact]
public void Sum()
{
    var result = sum(1, 2, 3);

    Assert.Equal(6, result);
}

[Fact]
public void Sum_PartialApply_FirstParam()
{
    Func sum1 = (y, z) => sum(1, y, z);

    var result = sum1(2, 3);

    Assert.Equal(6, result);
}

[Fact]
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.

Scala

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 {
    op(writer)
  } finally {
    writer.close()
  }
}

This is how it's called:

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

C#

Now I extended the definition with currying:

readonly Func, string>> openFile = 
    path => 
        handler =>
            {
                var reader = new StreamReader(path);
                try
                {
                    return handler(reader);
                }
                finally
                {
                    reader.Close();
                    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();

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

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

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#:

[Fact]
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

Currying

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

[Fact]
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#:

[Fact]
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.