Bookmark and Share

Continuation-Passing Style Overload

by KodefuGuru 25. August 2010 01:23

I wrote about continuation-passing style in a post a couple of months ago, and I’ve had time to ruminate over it since. One consideration I had is whether to return a type or not. This is easily handled by overloading the method.

static void Main()
{
    var result = Div(16, 3, (q, r) => new { Quotient = q, Remainder = r });
    Console.WriteLine("quotient: {0}", result.Quotient);
    Console.WriteLine("remainder: {0}", result.Remainder);

    Div(20, 3, (q, r) => Console.WriteLine("\nquotient: {0} \nremainder: {1}", q, r));
}

public static T Div<T>(int dividend, int divisor, Func<int, int, T> func)
{
    Contract.Requires(divisor != 0);
    Contract.Requires(func != null);

    var quotient = dividend / divisor;
    var remainder = dividend % divisor;

    return func(quotient, remainder);
}

public static void Div(int dividend, int divisor, Action<int, int> action)
{
    Contract.Requires(divisor != 0);
    Contract.Requires(action != null);

    var quotient = dividend / divisor;
    var remainder = dividend % divisor;

    action(quotient, remainder);
}

The first block of code inside of the Main method returns an anonymous type with Quotient and Remainder properties that are then printed to the screen. The second block passes the continuation action to the method. The purpose of the second version is create side-effect, in this case I’m writing to the screen, but in C# world this is sometimes necessary and beats the uglier code you will end up with if you attempt to do it with the function type.

But is the action really necessary? In my mind, Action<int, int> should be the same thing as Func<int, int, void>. I posted a message about this on twitter, and received a response that return type can’t be nothing. But here’s the rub… void isn’t nothing. The void keyword actually refers to the System.Void type. When you define a void method and return out of it, it returns a Void. This is object-oriented land, everything is an object; even void.

It would be neat if this could work as there would be no need for an action overload. If the lambda performed an action, void would be returned automatically. Basically, with void functions the second block of code in Main would make the second call have the following calling signature (with T replaced):

public static void Div<void>(int dividend, int divisor, Func<int, int, void> func)

This works great for generic continuation-passing methods. This actually works fine for any type of generic method with a tail function (a tail function is at the end). Upon further thought, I realized it’s terrible when the function wasn’t the tail.

If this were to exist, what would you do if someone were to assign a variable within the method?

public static void WriteDiv<T>(int dividend, int divisor, Func<int, int, T> func)
{
    Contract.Requires(divisor != 0);
    Contract.Requires(func != null);

    var quotient = dividend / divisor;
    var remainder = dividend % divisor;

    var ret = func(quotient, remainder);

    Console.WriteLine(ret);
}

I suppose ret would be an instance of System.Void, but what does it mean to write a void, which is nothing? It’s not the same as null… is more nothing than null. In fact, it can’t even be null because, well, it’s a struct.

Despite the fact it’s probably a bad idea, I attempted the impossible anyway. The C# compiler does not like you using System.Void, and it will not allow you to define void inside of generic parameters. So, I modded some IL!

Download the files

It assembles fine, and you can see it in reflector. However, I receive a runtime error when running it.

Unhandled Exception: System.TypeLoadException: The generic type 'System.Func`2' was used with an invalid instantiation in assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. at VoidFuncs.Program.Main()

It’s probably for the best that it doesn’t work. Any suggestions on how to make it work? I’m particularly looking for semantics as I believe that this could help promote functions to be first class citizens in C#.

Bookmark and Share

My First LightSwitch Failure

by KodefuGuru 18. August 2010 19:14

I used the prerequisite installer to make sure LightSwitch would be happy, then I installed the real thing. I then spun out a simple contact manager in a couple of minutes. It was amazingly easy to build an application that allows you to search contacts, add new contacts, and edit contacts. Unfortunately, I built the solution to encounter errors (without any code)!

Error 2 The type or namespace name 'RoundtripOriginalAttribute' does not exist in the namespace 'System.ComponentModel.DataAnnotations' (are you missing an assembly reference?) 56 c:\Projects\Application1\Application1\ClientGenerated\GeneratedArtifacts\DataClientImplementation.cs 34 ClientGenerated

Along with several other errors related to references. I could not find an add reference button, so I added it to the project manually (I verified the assembly was in the GAC). It still did not work.

I uninstalled WCF RIA Services for Visual Studio 2010 (installed by the prerequisite installer), then used the installer from Silverlight.net. That fixed the problem. I don’t know if it was a fluke with my system or if others will encounter this problem, but it’s easy enough to correct.

*UPDATE*

The correct dll (System.ServiceModel.DomainServices.Server.dll) isn't in the GAC. I was looking at the wrong assembly. WCF RIA Services for Visual Studio 2010 was installed at the time, however, and there didn't appear to be any problems with it. I don't want to dig deeper when it was likely something wrong with the installation, so if you experience the problem, just reinstall RIA Services.

*UPDATE 2*

This isn’t limited to my machine, and there is another invalid state you can reach. I posted this issue in the Lightswitch forums and Kris Langhor responded.

Thanks for the information. This is an issue that we are currently working to address for a future release.  The issue is related to the install order of the components. The Lightswitch prerequisites are specifically designed for provisioning a server that will not have the Lightswitch IDE installed on it. They install the WCF Ria Services bits in a Server-only mode that does not contain all of the assemblies. For a development machine you need only run the Lightswitch Web Install or setup from the CD.  That will install the full WCF Ria Services stack that is required by the designer.

When you follow the install steps that you have outlined you will get 1 of 2 results:

1) You end up in the state the you arrived at where Lightswitch installs but has compile errors. To work around that you need to uninstall WCF Ria Services and reinstall as you outlined.

OR

2) The Lightswitch install will report an install error and report it failed to install WCF Ria Services. In this case you should uninstall the version of Ria Services that is installed on your machine and then re-run the Lightswitch installer.

Hopefully this helps clarify the issue and provides folks wiht sufficient infromation to help workaround the issue.

This is a Beta, so don’t expect everything to work perfectly! I put this on my blog and posted to the forums to help others out who may run into the same problem.

Bookmark and Share

Int32 + String = String

by KodefuGuru 16. August 2010 19:18

This past weekend, we were throwing around C# trivia at a bar in Baton Rouge after SQL Saturday #28. Another speaker asked me one that he used in his session that day: what happens if you call Console.WriteLine(5 + “5”). I nonchalantly replied, “the number 55 written to the console.”

It really never occurred to me to attempt to add an int to a string, so I encountered this behavior in the context of something a little more bizarre: creating LINQ to Object. Here’s the extension method I used.

public static TResult SelectMany<TSource, TCollection, TResult>(this TSource source, 
    Func<TSource, TCollection> collectionSelector, 
Func<TSource, TCollection, TResult> resultSelector) { return resultSelector(source, collectionSelector(source)); }

There’s nothing particularly special about this extension method, but it allows you to combine two objects in a query expression. My first test was with types of the same kind.

[TestMethod]
public void SelectMany()
{
    var result = from x in 2
                 from y in 3
                 select x + y;

    Assert.AreEqual(5, result);
}

I know, that’s a really long-hand way to write 2 + 3. However, it proved that the SelectMany extension method worked. I then attempted it with an integer and a double. By all the rules, it should return a double.

[TestMethod]
public void SelectManyDifferentTypes()
{
    var result = from x in 2
                 from y in 3.1
                 select x + y;

    Assert.AreEqual(5.1, result);
}

Again, this was worked as I thought it would. But as I played with modifying the test to do an integer and a string, I noticed that it still compiled without any modifications to the select clause. Here’s the final test.

[TestMethod]
public void SelectManyIntAndString()
{
    var result = from x in 4
                 from y in "2"
                 select x + y;

    Assert.AreEqual("42", result);
}

I was dumbfounded. Was the act of passing the types through functions working magic with the types? I had to test it out on straight code to find out.

[TestMethod]
public void IntAndString()
{
    var result = 4 + "2";

    Assert.AreEqual("42", result);
}

There is no magic, unless you believe the compiler is a mystical force that binds all your code together. This is one of the compiler rules I had not encountered simply because it never occurred to me to add an int and a string together. I was expecting a type mismatch, but I missed one simple rule about strings buried deep in the C# specifications.

Whenever you use the + operator with a string, a string concatenation is performed. With a type that isn’t a string, this ends up calling String.Concat(object, object), which will use the ToString method of the object. If the parameter is null, String.Empty is used. You know all those places where you see “Hello “ + World.ToString() + “!!!”; completely unnecessary call to ToString().

Just because you know this works doesn’t mean you should do it. Readability of code is more important that doing tricks with strings. I would recommend calling ToString() when concatenating, prefering String.Format over concatenation, and using StringBuilder with large amounts of strings. But hey, it makes a great trivia question.

Tags:

Kodefu

Bookmark and Share

Is That Closure or Inheritance?

by KodefuGuru 10. August 2010 19:09

In response to my previous story, a commenter asked if the code I posted works due to a closure relationship rather than inheritance. The argument is that the field can be accessed by a nested class, and it wasn’t actually passed as a member to the other class. The reader of the story states that the field would still be accessed in Java even if Employee didn’t inherit from Person. Then, the question is asked if it’s different in C#.

I’m not familiar enough with Java to speak about how it works, but I can discuss what is happening in C#. First, let’s take a look at the code in question.

public class Person
{
    private string message;

    public override string ToString()
    {
        return message;
    }

    public static Person CreateEmployee()
    {
        return new Employee();
    }

    class Employee : Person
    {
        public Employee()
        {
            this.message = "I inherit private members!";
        }
    }
}

The reason you can be sure the constructor of Employee modifies the member named message on the instance of employee is because of the ‘this’ keyword. This keyword refers to the current instance, and this is the reason I don’t bother with underscores or funky names in my fields. If I need to scope to a member field, using the ‘this’ keyword is clearer than semantic customs… plus it has compiler support! Using ‘this’ within a nested type only refers to members of that type, and not the outer type

Of course, I use the keyword for convention, it oftentimes isn’t necessary. What happens If I remove the ‘this.’ from ‘this.message’?

public Employee()
{
    message = "I inherit private members!";
}

It still compiles, but whereas the answer was clearly “it’s inheritance” before, the lack of the keyword brings lack of clarity. So what’s happening? We could bring it up in reflector, but it would be more fun to modify the code. Let’s actually strip the inheritance hierarchy. This will require a few other modifications.

public class Person
{
    private string message;

    public override string ToString()
    {
        return message;
    }

    public static Employee CreateEmployee()
    {
        return new Employee();
    }

    public class Employee
    {
        public Employee()
        {
            message = "I inherit private members!";
        }
    }
}

And we find out quickly enough that this is will not work. Despite the lack of ‘this’, message was referring to the private member on Employee. Since Employee no longer inherits from Person, it is trying to access the field in the outer class. This gives us a rare error message.

Cannot access a non-static member of outer type 'Person' via nested type 'Person.Employee'

There’s a very simple explanation for this. Employee has been nested inside of Person. Just because you have an instance of the nested type does not mean you will have an instance of the outer type. Nesting allows for interesting accessibility scenarios, but there is no other special relationship defined.

The accessibility relationship works like this. I can create a method inside of Employee to access a private member of Person.

public class Employee
{
    public void Demo()
    {
        var person = new Person();
        person.message = "accessed";
    }
}

In the original version, it is possible to access the message field of Person from Employee if the message field is static as no instance is required.

I am not sure how this all works in Java, but my original example demonstrated inheritance with private accessibility. Try it out for yourself!

Bookmark and Share

Are Private Members Inherited?

by KodefuGuru 9. August 2010 17:30

When I interview someone, I start the question phase with simple object-oriented questions to get a feel for the person. Am I interviewing someone who writes rote procedural code or do I have someone in front of me who thinks in terms of objects and relationships. Even more intriguing, am I talking to a functional wunderkind who will enlighten me in my own journey through code? I start off with the simplest of questions: what’s the difference between a class and an object? Of course, the topics usually end up deep into their own experience as I use technical questions for the response factor more than right or wrong answers. I’m more interested in the fact that someone is thoughtful, into programming, and able to learn rather than whether they memorized a textbook or interview prep site.

A person came to me today to ask me a question they had recently in an interview for a C# position: are private members inherited? The answer given was no, and the interviewee was promptly informed that answer was incorrect.

On one level, it would appear that classes don’t inherit private members. Public and protected members are accessible by the subclass, but those pesky privates seemingly can’t be accessed. Of course, they’re there, otherwise calls to the exposed methods would not work. Then, there’s always reflection to access them. But I’m not really concerned about reflection or lower-level activities such as memory access; I’m more interested in the higher level concept of inheritance. Is the private member passed on to the subclass?

The problem with the private member isn’t actually one of inheritance, it’s one of accessibility. Being a private member means it’s only accessible within its defining type. To discover if the private members are inherited, we can set up a simple test: define the subclass within its parent.

public class Person
{
    private string message;

    public override string ToString()
    {
        return message;
    }

    public static Person CreateEmployee()
    {
        return new Employee();
    }

    class Employee : Person
    {
        public Employee()
        {
            this.message = "I inherit private members!";
        }
    }
}

Run this within a Console application, and it will print the message on the screen: “I inherit private members!”

class Program
{
    static void Main()
    {
        Console.WriteLine(Person.CreateEmployee());
    }
}

Proof positive that private members are actually inherited. Remember, modifiers such as public, protected, private, and internal are all accessibility modifiers. These modifiers affect encapsulation rather than inheritance.

A class takes everything from its parent class; its instantiation will have every member. In most situations, those marked private are hidden from from the subclass. Using reflection follows this same behavior: with the example above, message will not be returned through type.GetMembers(BindingFlags.NonPublic|BindingFlags.Instance) despite the fact that it has been exposed.

I do, however, feel that the concept of encapsulation and inheritance coexist and are intertwined. Certainly, at a physical level, the instance of the object has the same memory, and therefore can access the functionality that has been hidden from it through the interface its parent has given it. But conceptually, one does not look at a class and consider members that have been hidden from view as being part of it. Instead, we think of a class as inheriting an interface and behavior, not the entire template. I may inherit my parents’ features, but their secrets are theirs to keep.

I did demonstrate a way to break the way many think about inheritance in C#. Some languages don’t allow access beyond the public interface even to their subclasses. In those languages, inheritance doesn’t break encapsulation, and I believe the case is stronger that encapsulation makes our conceptual view more valid. Don’t get me wrong though, the accessibility modifiers in C# are very useful, and I wouldn’t trade them for a more “pure” language.

If I were the one asking the interview question, I would not be interested if the candidate got the question right with a simple yes or no answer. I would ask why in either case. Most people probably would respond that “objects can’t access private members of the parent class,” despite the fact that I’ve proven it can be done. Does that make the person a bad developer? No, because that is true in nearly all situations, and it describes, without being too technical, encapsulation. That would be a good time for me to follow up with encapsulation. What if instead the person knew how to access the parent’s private members through inheritance, then proceeded to provide more information about encapsulation and inheritance? Well, kudos, maybe you read my blog? In all seriousness though, if someone came back to me with that information I would be impressed simply because they care enough about their craft to learn it, just as I am impressed when someone cares enough to discuss these topics at conferences because they are truly interested in learning.

Bookmark and Share

Remove Generic Parameter Refactoring

by KodefuGuru 6. August 2010 12:30

I needed to remove an extraneous generic parameter from two classes in a 2008 project. One of the classes was BusinessObjectList<TList, TItem>, and TList wasn’t used and it ended up junking up the code throughout the solution. I was tired of looking at it and its bizarre subclasses like EmployeeList : BusinessObjectList<EmployeeList, Employee>.

I will note how it could be useful: if any of the methods on BusinessObjectList were returning the subclassed list as part of a fluent interface. But nothing like this exists. I’m not even a fan of defined list classes. Why should you limit yourself when there are other sequence possibilities? What if I had an array of the particular BusinessObject?  I think extension methods on IEnumerable<BusinessObject> are better and it plays better with LINQ (I don’t have to redefine every LINQ method to make it return the list). These are fluent by their nature anyway since you typically make the method yield out the objects creating an IEnumerable<T>.

But, the hard lists are there, and I believe the cost of removing them is too high at this point in time but it’s something I’ll have my eye on if the opportunity exists. Keeping the code tight by removing the extraneous generic is worth it though considering some other framework issues I will be tackling. The problem is that hundreds of classes inherited from this class and the other, and a manual edit would take forever. This refactoring should be quick.

I checked all of my tools, but none had a “remove generic parameter” refactoring. Would I have to do this by hand? Of course not, I’m a programmer. What tool do we have for matching stuff like a BusinessObjectList<X, Y>? How about RegEx?

I pop up the Find/Replace dialog, and immediately type a regex that should match everything I want to replace. It doesn’t work. Now, I’m not an expert in that sort of thing, but surely I can write something that simple? After a few minutes of trying it out, I start searching and discover Jeff Atwood has already talked about this oddity in Visual Studio.

After learning Visual Studio’s flavor of regex, I finally achieved a somewhat bizarre construct for removing a generic parameter. Find what: BusinessObjectList\<:i,:b{:i}\> and Replace with: BusinessObjectList\<\1\>.

clip_image002

The class everything was inheriting from was BusinessObjectList, so I wrote that in and escaped the < and >. :i marks a C/C++ identifier (which works great with C#!) and :b matches tab or space. I enclosed the second :i with curly braces so I could use it as an identifier in the replace regex with \1.

There may not have been a fancy tool to achieve this, but the results were the same and it didn’t take much time. It certainly beats replacing the code by hand.

Bookmark and Share

First Look at the Razor CSharp HTML File in MVC 3

by KodefuGuru 2. August 2010 12:05

The day before I left for IEEE ICCSIT 2010, there was a huge announcement about a new view engine for ASP.NET: Razor. It was old news by the time I returned, but I couldn’t help but sit down and play with it. I skimmed a few a blog postings on it, but I wasn’t getting anything good. So, I downloaded the ASP.NET MVC 3 Preview 1 and began playing with it myself.

After installing the preview, I created a new ASP.NET MVC 3 Razor application. I then proceeded to open the Views/Home/Index.cshtml to see what it created for me.

@inherits System.Web.Mvc.WebViewPage

@{
    View.Title = "Home Page";
    LayoutPage = "~/Views/Shared/_Layout.cshtml";
}

<h2>@View.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" 
title="ASP.NET MVC Website">http://asp.net/mvc</a>. </p>

The one thing I did pick up from skimming the blogs was that the @ symbol is the directive to replace all the <% %> symbols. From that, a few things become clear. The compiled class must not have a name, but it inherits from System.Web.Mvc.WebViewPage. Placing @ in front of curly braces enters a block, just like in regular code. WebViewPage has a View property and a LayoutPage property (which I assume replaces the MasterPage concept). And finally, accessing a variable in the middle of HTML works exactly like you’d expect.

The View.Title is a little fishy to me. WebViewPage does not define a generic class for the Model, and I don’t see any signs of the ViewData. I’m going to go out on a limb here and guess it's an ExpandoObject. Let’s open up WebViewPage with reflector and find out.

public dynamic View
{
    get
    {
        Func<ViewDataDictionary> viewDataThunk = null;
        if (this._dynamicViewData == null)
        {
            if (viewDataThunk == null)
            {
                viewDataThunk = () => this.ViewData;
            }
            this._dynamicViewData = new DynamicViewDataDictionary(viewDataThunk);
        }
        return this._dynamicViewData;
    }
}

Well, it’s not exactly an ExpandoObject, but it is dynamic. Instead of sticking values in itself, it’s sticking values in the ViewData dictionary. This means you can treat it like an ExpandoObject. I wrote View.Duck = “Quack”; on the line after View.Title, then I put <h3>@View.Duck</h3> at the bottom of the page. It worked like a charm.

The layout page contains what one would expect from a layout page. It contains the primary html that embodies the site including the head, the body, the menu, and the footer. The primary thing here is that it renders the body of the view by calling @RenderBody().

<div id="main">
    @RenderBody()
    <div id="footer">
    </div>
</div>

The standard calls to the Html helper methods are in place, so there isn’t much to learn there.

<div id="logindisplay">
    @Html.Partial("_LogOnPartial")
</div>

<div id="menucontainer">

    <ul id="menu">
        <li>@Html.ActionLink("Home", "Index", "Home")</li>
        <li>@Html.ActionLink("About", "About", "Home")</li>
    </ul>

</div>

I know this could become more complicated when switching contexts from C# to HTML. However, if you’ve written complicated views with the aspx engine, it can already be messy. I’m confident from what I’ve seen so far that Razor cleans it up tremendously. What I find intriguing is the ASP.NET MVC team is starting to innovate with the .NET 4 language features. I can’t wait to dig deeper to see what they’ve done.

Bookmark and Share

Unpack and Transform Tuples with CPS

by KodefuGuru 28. July 2010 17:13

The tuple class made its debut in the .NET framework along with a language that supports it well: F#. But being a first-class citizen of the framework means other languages have access to this data type as well. Unfortunately, neither C# nor VB obtained any language support for tuples, and it ends up being treated as a dumb, generic data container instead of the powerful data class that is oftentimes found in functional languages.

Accessing the elements of a tuple is rather bland, as each piece is named sequentially Item1, Item2, and so on. Compare this to an anonymous type, essentially the same sort of class, where each element has been given a name. The only way to unpack a tuple in C# is to assign each item property to another variable or object property. Of course, this leads to rote assignments which junks up code.

I have no way to modify the compiler to act more like F#. However, there are some techniques we can use to make working with tuples a little easier in C#. Extension methods allow us to assign functionality to a tuple. In this case we want tuples to be able to unpack and transform themselves. With continuation-passing style, the tuple can pass its values to a lambda that we define, thereby eliminating the ugly ItemX syntax.

Each extension method will require overloads for each generic version of Tuple. For the examples, I will be demonstrating the triple.

public static void Unpack<T1, T2, T3>(this Tuple<T1, T2, T3> tuple, Action<T1, T2, T3> action)
{
    action(tuple.Item1, tuple.Item2, tuple.Item3);
}

Unpack allows the caller to assign the items of the tuple to other variables or properties of an object. Let’s take a look at the unit test.

[TestMethod]
public void Unpack()
{
    var tuple = Tuple.Create(1, 2, 3);
    int x = 0;
    int y = 0;
    int z = 0;

    tuple.Unpack((a, b, c) => { x = a; y = b; z = c; });

    Assert.AreEqual(1, x);
    Assert.AreEqual(2, y);
    Assert.AreEqual(3, z);
}

Item1 becomes a, Item2 becomes b, and Item3 becomes c. We then take our named elements and unpack them into the variables we desire. There is no concept of no match; if you don’t want to unpack one of the variables, don’t assign it to something. You could use the _ one time to indicate non-usage as _ is a valid variable name in C#. E.g. tuple.Unpack((a, _, c) => { x = a; z = c; });.

What if we want to do more than unpack… say transform the tuple into another type?

public static TResult Transform<T1, T2, T3, TResult>(this Tuple<T1, T2, T3> tuple, 
Func<T1, T2, T3, TResult> func) { return func(tuple.Item1, tuple.Item2, tuple.Item3); }

Here’s the test to show how it works.

[TestMethod]
public void Transform()
{
    var tuple = Tuple.Create(3, 4, 5);
    var triangle = tuple.Transform((a, b, c) => new {Width = a, Height = b, Hypotenuse = c});
    
    Assert.AreEqual(3, triangle.Width);
    Assert.AreEqual(4, triangle.Height);
    Assert.AreEqual(5, triangle.Hypotenuse);
}

This is very similar to Unpack, but it returns an object instead. This allows you to create a new object, or assign properties on an existing object and continue a method chain.

I hope continuation-passing style helps you out if you must work with tuples in C#. Of course, if you have heavy processing of tuples, it may be time to switch to a language that handles them better... at least for that particular project.

Bookmark and Share

Summation Functions

by KodefuGuru 26. July 2010 17:31

Creating a summation function in C# isn’t difficult in itself. After all, it is perfectly reasonable to create functions that consist of more than one line. What is interesting is abstracting it so that any function can become a summation function.

Here is the Madhava-Leibniz function for pi:

Madhava-Leibniz Formula for Pi

Here’s how we can define the inner function:

Func<Int32, Double> f = k =>  4 * (Math.Pow(-1, k) / ((2.0 * k) + 1));

What we want to be able to do is call f.Sum(). This will generate a summation function that calculates pi. Here’s how we accomplish that task.

public static Func<Int32, Double> Sum(this Func<Int32, Double> func, int start = 0)
{
    return end =>
    {
        Double result = default(Double);

        for (int k = start; k <= end; k++)
        {
            result += func(k);
        }

        return result;
    };
}

We need to accumulate the results of every pass into the function. The resulting summation function will still require a parameter representing the upper bound. This is because we actually do need to return at some point in time to inspect the result.

Here’s the test to prove this works.

[TestMethod]
public void Pi()
{
    Func<Int32, Double> f = k =>  4 * (Math.Pow(-1, k) / ((2.0 * k) + 1));
    var calculatePi = f.Sum();
    Assert.AreEqual(3.14159, calculatePi(200000), 7);
}

With 200,000 passes, we can ensure an accuracy of 7. Leibniz didn’t rediscover the most efficient way of calculating pi, but it works for a test of the Sum extension method.

If we switch context to VB, we can even use this with a query expression! A couple of things. 1) VB 10 has a bug and can’t handle the optional parameter… change it to a traditional overload and 2) we need a Cast method.

I’ll let you figure out how to make a traditional overload. The cast method won’t actually do anything (because it will break the function), but we need it because the query expression will try to use it.

public static Func<T, TResult> Cast<TCast, T, TResult>(this Func<T, TResult> func)
{
    return func;
}

Here’s the VB test that uses LINQ!

<TestMethod()>
Public Sub Pi()
    Dim f As Func(Of Integer, Double) = Function(k) 4 * (Math.Pow(-1, k) / ((2.0 * k) + 1))
    Dim calculatePi = Aggregate x In f Into Sum()
    Assert.AreEqual(3.14159, calculatePi(200000), 7)
End Sub

I think it’s easier to just call f.Sum(), but this should give you a taste of where I will be taking things with future articles.

Download the source code from CodePlex!

Bookmark and Share

Call a Function to Infinity

by KodefuGuru 23. July 2010 17:43

What if the resulting value of a function was used to feed the parameter of the same function? It’s easy enough to call a function, get its result, then pass it back in. However, I wanted to abstract this and make it work for anything whose generic parameter type is the same as the generic result type. If it’s abstracted, there must be some arbitrary end point… right? How about infinity?

I thought about it, then dreamed up a solution involving 3 of our friends we see so often:

1) Func<T, T>
2) Iterator Pattern
3) Extension Method

I then wrote a simple unit test to prove my work.

[TestMethod]
public void Iterate()
{
    Func<Int32, Int32> f = x => x + 1;
    var nums = f.Iterate(1).Take(10);
    Assert.AreEqual(10, nums.Last());
}

There’s a function that adds a number to the parameter. We want to call the Iterate method on the function, passing in the initial value of 1. Then we must take 10 because it will never stop. Given the parameters, the last number should be 10.

Great. With a test available, I went about creating the code.

public static IEnumerable<T> Iterate<T>(this Func<T, T> func, T value)
{
    while (true)
    {
        yield return value;
        value = func(value);
    }
}

This is going to create a sequence of all the values. Since the initial value may be used (it was in my test), I decided to return it. If you have a graphing function that begins at 0, you would probably want 0 in your list of values. The yield return keyword creates an iterator, and the extension method allows it to appear as though Iterate() was a method that belonged to the function anyway.

After I wrote this code, I called up a friend to explain that I finally got around to creating an infinite iterator. When I told him the function was being called repeatedly, being fed it’s resulting value, he mentioned that I would get a stack overflow as though I were making extremely deep, recursive method calls. I disagreed due to the way it was implemented.

I wrote a test to see if I would have this kind of issue.

[TestMethod]
public void IterateShouldNotStackOverflow()
{
    Func<Int32, Int32> f = x => x;
    foreach (var n in f.Iterate(1))
    {
    }
}

I started it up and watched it for a bit. Then I grabbed some coffee, came back, watched it for a bit. Eventually, I grew bored with it. I then set the test to ignore because it is a terrible automated test candidate.

If you run this, remember that it returns an infinite IEnumerable<T>. You should never run an aggregate method on it, and you should never just foreach over it without some termination condition. Iterate() is meant to be used in conjunction with Skip, Take, First.

Here’s the source code to this and other extensions on functions.

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
C# MVP, INETA Community Champion


MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er

I have joined Anti-IF Campaign


World Map

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010