Infinite ranges in C#

Posted by Jonas Elfström Tue, 20 Oct 2009 18:41:00 GMT

I recently learned that C# is compliant with the IEEE 754-1985 for floating point arithmetics. That wasn't a big surprise but that division by zero is defined as Infinity in it was! It actually kind of bothers me that I didn't know this.

In mathematics division by zero is undefined for real numbers but I guess Infinity is a more pragmatic result. Or as a friend put it "IEEE stands for Institute of Electrical and Electronics Engineers not Institute of Mathematics"

1
2
3
4
double n = 1.0;
n = n / 0;
if (n > 636413622384679305)
  System.Console.WriteLine("Yes it certainly is!");

This C# code does not throw an exception, it simply leaves n defined as Infinity and a line written to the console.

Ruby is also IEEE 754-1985 compliant. It even lets you define infinite ranges.

1
2
3
4
5
6
Infinity=1.0/0
=>Infinity
(1..Infinity).include?(162259276829213363391578010288127)
=> true
(7..Infinity).step(7).take(3).inject(&:+) # 7+14+21
=> 42


I can't say I see very much use of this but it brings a kind of completeness to the handling of infinities. Unfortunately it seems we don't get that in C# out of the box because Enumerable.Range takes <int>,<int> as parameters and there's no Infinity definition for int. That's unless someone wrote a generic Range class. Turns out none other than Jon Skeet did in his MiscUtil. Dowload MiscUtil and then by using MiscUtil.Collections; you can:

1
2
3
4
5
6
double n = 1.0;
var infinity = n / 0;
var r = new Range<double>(0, infinity);
if (r.Contains(4711))
  System.Console.WriteLine("Yes it certainly does!");
var sum = r.Step(7.0).Take(3).Sum();


And guess what, it works like a charm! 4711 is part of positive infinity and sum is 42.0 and all is good.

Edit

There's also a couple of predefined constants. Thanks to Eric for pointing that out.

1
2
var r = new Range<double>(7,  System.Double.PositiveInfinity);
var sum = r.Step(7.0).Take(3).Sum();

Posted in , ,  | 1 comment

The Thrush combinator in C#

Posted by Jonas Elfström Tue, 06 Oct 2009 18:35:00 GMT

Last year I read Reg "Raganwald'" Braithwaite's excellent post The Thrush and he explains it as

The thrush is written Txy = yx. It reverses evaluation.

Back then I didn't even consider trying to implement it in C#. That was before I digged deeper into lambda expressions and extension methods in C# 3.0 and way before last night when I read Debasish Ghosh's post on how to implement the Thrush in Scala. After reading that my first thought was if it was possible to do the same in C#. Here's my attempt.

At first I struggled with the static typing and headed for an easy way out using Object in the extension method of Object:

1
2
public static object Into(this Object obj, Func<object, object> f)
{  return f.Invoke(obj); }


My goal was to translate the Ruby example


(1..100).select(&:odd?).inject(&:+).into { |x| x * x }

in Raganwald's post to C#.

Which reads "Take the numbers from 1 to 100, keep the odd ones, take the sum of those, and then answer the square of that number."

But with the Object based extension method I had to do some ugly casts.


var r = Enumerable.Range(1, 100).Where(x => Odd(x)).Sum().Into(x => (int)x * (int)x);


With som added typing I could do:


var result = Enumerable.Range(1, 100).Where(x => Odd(x)).Sum().Into(x => x * x);


But that merely moved the cast to the ext. method and also made it work for integers only.

1
2
public static int Into(this Object obj, Func<int, int> f)
{ return f.Invoke((int)obj); }


Then I remembered generics and method type inference.

1
2
public static T Into<T>(this T obj, Func<T, T> f)
{ return f(obj); }

And now not only the casts were gone but I also got a thrush combinator almost as flexible as the one in Ruby.

Contrived example follows:

1
2
var test = "ball";
var ball = test.Into(s => "Are we having a " + s + " yet?");
 

The odd part

The Odd(x) method call in the calculation above is a plain static method.

1
2
private static bool Odd(int n)
{ return (n % 2 != 0); }

If you want an even more terse syntax you could try an ext. method on IEnumerable like this:

1
2
public static IEnumerable<int> Odd(this IEnumerable<int> en)
{ return en.Where(n => n % 2 != 0); }

Gives:


var result = Enumerable.Range(1, 100).Odd().Sum().Into(x => x * x);


Also as a general alternative to .Sum() I could have used .Aggregate((x, y) => x + y)) but I found it a bit verbose.

In C# I don't think it's possible to pull off the Symbol#to_proc stuff that Ruby does. That's the &: in the select(&:odd?) and the inject(&:+) in the Ruby example. Raganwald has a great post on that too.

Edit

Check out Jon Skeet's nice answer on StackOverflow to my question on how to make this even more Ruby-like. I have to try out that Operator class later though.

Edit 2009-10-07

One thing I found a bit surprising is that by implementing the Into ext. method in this way it not only works for all objects based on System.Object but it also works for value types.

1
2
3
4
int n=4711;
int oddOrZero = n.Into(x => x % 2 !=0 ? x : 0); // 4711
n = 4712;
oddOrZero = n.Into(x => x % 2 != 0 ? x : 0); // 0


Edit 2009-10-12

My confusion did stem from my lack of understanding of extension methods. Ex. methods are in fact not extending System.Object or any other type, they are "nothing more than a pleasant syntax for calling a static method" in case no instance method with the same name can be found.

Posted in ,  | 1 comment

No var for me in the foreach

Posted by Jonas Elfström Tue, 09 Jun 2009 20:24:00 GMT

In C# 3.0 we got type inference or implicit typing as Microsoft likes to call it. As a Ruby programmer I've got a thing for essence over ceremony and those repetive declarations in C# (and Java) has always bothered me. So of course I quickly put var in my tool belt. If I want to create a certain object why should I have to state that twice?

1
2
3
4
// C# 2.0
Dictionary<Customer, List<PhoneNumber>> phonebook = new Dictionary<Customer, List<PhoneNumber>>(); 
// C# 3.0
var phonebook = new Dictionary<Customer, List<PhoneNumber>>();

Still you should use it with care. I've seen:

1
2
var i = 5;
var s = "This stmt is unprovable!";

And frankly, I do not agree.

A couple of days ago I almost thought I found a bug or limitation in the C# compiler. Something like the following would not compile:

1
2
3
4
5
6
7
String html = "<a href='http://is.gd/Uoip'>Recursion</a>,\r\n" +
              "see <a href='http://is.gd/Uoip'>recursion</a>.";
String links="";
var matches = Regex.Matches(html, "(a href=')(.*)('>)");
foreach (var match in matches) {
    links+=match.Groups[2]+"\r\n";
}

The compiler complained that Object had no Groups method. How come it could not see that Regex.Matches returned a MatchCollection and that that collection was populated with Match objects? Then it dawned on me. Back in the dark ages of C# 1.x we did not have generics. MatchCollection is an old class that implements ICollection and not ICollection(T) so the compiler could not infer the type. A quick change to:


foreach (Match match in matches) {

and we were good to go.

Posted in  | no comments

Get the value of and with using the null-coalescing operator

Posted by Jonas Elfström Fri, 15 May 2009 22:38:00 GMT

I like the ?? operator that surfaced in C# 2.0. I'm often in environments where null values florish and ?? is a great way to handle them, especially for presentation. A while ago I found a use for the ?? operator in a way I'd never used it before.

The problem at hand was to return an account number from data that could be described as somewhat inconsistent.

The application had left room for the users to enter accounts in two by two ways. A customer could have multiple subsidiaries and in each subsidiary, by misconception, two different fields had been used as the account number. It was also possible to connect an account to all subsidairies of a customer at the same time as a specific subsidiary of that customer had an account defined.

Only if a unique account could be found it should be returned. All other cases should return a cause of failure so that the users could use that information to clean up the mess.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private static Account GetCustomerAccount(Customer customer)
{
  bool hasAccount = !String.IsNullOrEmpty(customer.AccountNo);
  bool hasAccountNoExtra = !String.IsNullOrEmpty(customer.AccountNoExtra);
  bool hasAllSubsAccount = !String.IsNullOrEmpty(customer.AccountNoAllSubs);
  bool hasAllSubsAccountNoExtra = 
       !String.IsNullOrEmpty(customer.AccountNoExtraAllSubs);
  var account = new Account();

  if ((hasAccount || hasAccountNoExtra) &&
      (hasAllSubsAccount || hasAllSubsAccountNoExtra)) 
  {
    account.Status = account.HasBothAllSubsAndSpecific;
    return account;
  }
  if ((hasAccount && hasAccountNoExtra) ||   
      (hasAllSubsAccount && hasAllSubsAccountNoExtra)) 
  {
    account.Status = account.HasBothAccountAndAccountExtra;
    return account;
  }

  account.AccountNo = customer.AccountNo ??
                      customer.AccountNoExtra ??
                      customer.AccountNoAllSubs ??
                      customer.AccountNoExtraAllSubs;

  if (account.AccountNo==null)
    account.Status=account.HasNoAccountDefined;

  return account;
}


Notice how AccountNo is set to the first non null value of the four. Imagine that with plain ifs. Here I believe the ??-operator both makes the code clear and saves us from a bunch of nested ifs.

Posted in  | no comments

Predicate matches me

Posted by Jonas Elfström Thu, 29 Jan 2009 20:29:00 GMT

I really like the Predicate(T) delegates that were added to the generic collections and lists in .NET 2.0. With the later addition of lambda expressions came cleanliness and readability.

Today we faced a quite simple problem that were made even simpler by the dear predicates. We had a kind of event log and wanted to filter it client side (Windows Forms) using a list of criterias. We began by implementing to filter by a number of categories. It ended up being only one row (in Visual Studio, for obvious reasons not here):

1
2
3
4
5
6
private List<Events> FilterEventsByCategory(List<Events> events,
                                        List<Category> categories) 
{
  return events.FindAll(event => 
      categories.Exists(category => category.CategoryId==event.CategoryId)); 
}


Neat!

Posted in  | 1 comment

Older posts: 1 2