Monday, December 10, 2007

Happy Birthday!

Bethany Anne Campbell was born on December 9, 2007 at 10:40 a.m. At 5 weeks early, Bethany was definitely a big surprise. However, it was pretty clear that she was ready to join us on the outside. Once we arrived at the hospital, it was only thirty minutes before Bethany was born. I suppose that means that she'll always be one or two steps ahead of us.

posted on Monday, December 10, 2007 3:58:50 AM (Pacific Standard Time, UTC-08:00)  #    Comments [17]

kick it on DotNetKicks.com
 Friday, November 23, 2007
Visual Studio 2008's multi-targeting support for compiling projects to different versions of the .NET Framework is very powerful. Multi-targeting is a compelling feature because it enables users to continue working on solutions that target .NET Framework 2.0 and 3.0 while upgrading to the latest and greatest IDE. What isn't obvious is that all projects, regardless of target, are compiled with the C# 3.0 compiler. That means users can employ many of the new C# 3.0 language features in legacy projects. The only language features that can't be used are those that require library support from .NET Framework 3.5, in essence, LINQ, Expression Trees and Extension Methods. Implicitly-typed local variables, lambda expressions, auto-implemented properties, object and collection initializers, and anonymous types are all fair game. It's sort of like having C# 3.0-lite or C# 2.5.

Interestingly, it has recently been discovered that even Extension Methods can be used in projects targeting .NET Framework 2.0 and 3.0. All that must be done to enable this support is to create a new System.Runtime.CompilerServices.ExtensionAttribute.

using System;

namespace System.Runtime.CompilerServices
{
  public class ExtensionAttribute: Attribute
  {
  }
}

This trick does have flaws. There are potential scoping issues that occur when an assembly containing a custom System.Runtime.CompilerServices.ExtensionAttribute is referenced by a project that targets .NET Framework 3.5. A compiler warning is generated stating that "the predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias." However, this is only a minor irritation. In my tests, Extension Methods still worked properly despite the warning.

The ability to use C# 3.0 features in .NET Framework 2.0 or 3.0 projects is very powerful. It helps users get comfortable with the new syntax without having to upgrade projects to .NET Framework 3.5. Viva la C# 2.5!

posted on Friday, November 23, 2007 7:29:08 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Tuesday, November 13, 2007
While exploring F#, I've grown increasingly impressed by the libraries that ship with it. One of the main purposes of the libraries is to provide underlying support for the language itself. In addition, they contain important modules and classes necessary for functional programming (e.g. immutable List and Map types). However, the most practical aspect of these libraries to me is the rich set of APIs that facilitate using the .NET Framework in a more functional way. These APIs are often directly portable to C#. Let's look at a simple example.

The following C# code is typical of how we might create an array containing the natural numbers from 1 to 20:

int[] a = new int[20];
for (int x = 0; x < a.Length; x++)
  a[x] = x + 1;

There's nothing special about that code. It's representative of the sort of thing that we write all the time. However, it won't fly in the functional world because it's written in an imperative style. That is, the code specifies the exact steps that should be taken to create and initialize the array:

  1. Create a new int array of 20 elements.
  2. Initialize a new indexer variable, x, to 0.
  3. Check to see that x is less than the length of the array. If it isn't, STOP.
  4. Assign the value of the array element at index x to the result of x + 1.
  5. Increment x.
  6. GO BACK to step 3. Repeat as necessary.

In contrast, the F# libraries provide a special module, Array, for manipulating single-dimensional .NET arrays in a more functional style. (Array2 and Array3 are also available for manipulating two- and three-dimensional arrays respectively.) Using the Array module, the C# code above could be translated to F# like so:

let a = Array.init 20 (fun x -> x + 1)

Instead of a specific code recipe, this F# code says (in a more declarative fashion), "create an array of 20 elements, and use this function to initialize each element." An interesting feature of the F# version is that the type of the array is never declared. Because the compiler can infer that the result of the passed function (fun x -> x + 1) will be an int, "a" must be an int array.

To me, this code is beautiful. In addition, it is declarative instead of imperative; it describes what should be done but doesn't dictate exactly how it should be done. When I see such elegant code, I immediately start trying to figure out which of its aspects could be used to improve the code in my daily C# work. Here's how we might "borrow" the F# "Array.init" function in C#:

public static class ArrayEx
{
  public delegate T CreateItem<T>(int index);
 
  public static T[] Create<T>(int length, CreateItem<T> createItem)
  {
    if (length < 0)
      throw new ArgumentOutOfRangeException("length");
 
    if (length == 0)
      return new T[0];
 
    T[] result = new T[length];
    if (createItem != null)
    {
      for (int i = 0; i < length; i++)
        result[i] = createItem(i);
    }
    return result;
  }
}

With this function defined, we can rewrite our array creation sample declaratively using C# 3.0 syntax.

var a = ArrayEx.Create(20, x => x + 1);

Notice that this code takes advantage of the C# compiler's type inference in the same way that the F# sample does. Sweet!

Let's take a look at another example. Suppose we want to iterate through all of the elements in our int array and output each element's value to the console. We have a few of options available to us. First, there's the familiar for-loop approach:

for (int x = 0; x < a.Length; x++)
  Console.WriteLine(a[x]);

Second, there's the more declarative foreach-loop:

foreach (int val in a)
  Console.WriteLine(val);

Finally, the underused "Array.ForEach" BCL method is also a possibility:

Array.ForEach(a, val => Console.WriteLine(val));

In addition, because "Console.WriteLine" has an overload which accepts a single int parameter, we can rewrite the previous code without a lambda expression:

Array.ForEach(a, Console.WriteLine);

Now, for the monkey wrench. Suppose we want to print the index of each element in the array along with the value. With this added requirement, the for-loop is our most attractive choice because the indexer variable is already built in. The other two options would require awkwardly creating an indexer variable and explicitly incrementing it. This additional code looks especially ugly with the "Array.ForEach" option.

int x = 0;
Array.ForEach(a, val => Console.WriteLine("{0}: {1}", x++, val));

Nasty.

How might we handle this in F#? Simple. F# provides an API designed to iterate an array with an index.

Array.iteri (fun x value -> printfn "%i: %i" x value) a

Like the BCL's "Array.ForEach" method, F#'s "Array.iteri" iterates through an array and applies the given function to each element. The difference is that the function to be applied includes an additional parameter representing the element's index in the array.

NeRd Note
Curious about why the parameter ordering of the F# "Array.iteri" API places the function to be applied before the array to be iterated? Isn't that backwards? Wouldn't it make more sense to move the array parameter to the first position? Nope. The parameter ordering is intentional.

Unless specified, F# functions are implicitly curried. Hence, parameters are usually ordered to take advantage of partial application. If the parameters of "Array.iteri" were reordered, we could not easily use partial application to build useful functions from it.
let print = Array.iteri (fun x value -> printfn "%i: %i" x value)

print a
Besides, if passing "a" as the last parameter is awkward, we can always pass it with the F# pipeline operator.
a |> Array.iteri (fun x value -> printfn "%i: %i" x value)
Make sense? OK. Take a deep breath...

Using F#'s "Array.iteri" as a model, we can define an equivalent function in C#.

public static class ArrayEx
{
  public delegate void IndexedAction<T>(int index, T item);
 
  public static void Iterate<T>(T[] array, IndexedAction<T> action)
  {
    if (array == null)
      throw new ArgumentNullException("array");
    if (action == null)
      throw new ArgumentNullException("action");

    if (array.Length <= 0)
      return;

    int lower = array.GetLowerBound(0);
    int upper = array.GetUpperBound(0);

    for (int i = lower; i <= upper; i++)
      action(i, array[i]);
  }
}

Now we can iterate our array and output the index and value of each element to the console with one line of code!

ArrayEx.Iterate(a, (x, i) => Console.WriteLine("{0}: {1}", x, i));

Since we're using C# 3.0, we can declare "ArrayEx.Iterate" as an extension method to make the client code more readable.

a.Iterate((x, i) => Console.WriteLine("{0}: {1}", x, i));

In conclusion, using F# as a source of inspiration, it's easy to create APIs that enable more declarative C# code to be written. Do you have a cool declarative API that you've written for C# or VB? If so, I'd love to hear about it. Feel free to post your creations in the comments or email me directly.

posted on Tuesday, November 13, 2007 8:17:23 PM (Pacific Standard Time, UTC-08:00)  #    Comments [18]

kick it on DotNetKicks.com
 Thursday, November 08, 2007
Putting the Fun into Functional with F#

Scrambling to understand arcane-sounding functional programming terms like "closure" and "currying?" Intrigued by the recent community coverage of Microsoft's F# language, but don't know where to start? Look no further. This overview of functional programming is a wild ride through the five most important concepts using the elegant syntax of Microsoft F#. Note: no object-oriented programmers will be harmed during the session.

That's the session that I'll be presenting at the upcoming CodeMash conference. I'm really excited about this talk.

If you're planning on coming but haven't registered, the early bird discount will expire on November 15th.

See you there!

posted on Thursday, November 08, 2007 10:46:37 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
 Wednesday, October 31, 2007
My good friend, and fellow language lover, Jay Wren was recently interviewed for Code to Live. Jay has a very sharp mind and scary technical chops. He the sort of programmer who tosses around phrases like "Inversion of Control" in normal conversation. On Code to Live, he talks with Josh Holmes about the Boo programming language. Check out the interview here.

posted on Wednesday, October 31, 2007 11:27:12 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
In my recent post listing F# resources, I failed to mention the very best learning resource of all: the library source code. If you're having trouble figuring out how, say, Seq.fold works, take a look inside of ienumerable.fs to see how it's implemented. The libraries are filled with well-written code that can be used for learning and exploring this beautiful language.

posted on Wednesday, October 31, 2007 10:44:14 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
The following list is mostly for anyone looking for information on Microsoft's F# language and partly for myself, so I can find the links later.
  • The F# Home Page. This is the official home page for F# at Microsoft Research. Quite a bit of information can be found here, including download links for the F# distribution, the F# manual and the F# library reference.
  • hubFS. The forums at hubFS are a gold mine of information. This is where the F# authorities (like Don Syme himself!) answers questions.
  • F# Wiki. There are some great articles and tips here. Hopefully, this will expand as the interest around F# increases.
  • The F# Journal. This subscription-based online journal is maintained by well-known F# authority, Jon Harrop. The content is quite good, but unfortunately, the subscription is quite expensive. Currently, a six-month subscription is priced at £59. At today's exchange rate, that's approximately $122—an amazingly hefty price for an online journal. (For comparison, consider that an online subscription to Cambridge's Journal of Functional Programming only costs $135 per year for individuals.)
  • Don Syme's Blog. Don Syme is the creator and principal maintainer of F#. If you're learning F#, you must read his blog. It's a requirement. :-) Don's book, Expert F#, is available for pre-order and should be shipping sometime in Nov./Dec.
  • Robert Pickering's Blog. Robert Pickering is a heavyweight in the F# community. In addition, he is the author of the excellent Foundations of F#.
  • Jomo Fisher's Blog. Jomo is a member of the new F# team in Redmond. His blog contains many interesting articles that examine F# through the lens of C#.
  • Tomas Petricek's Blog. After spending some time in the hubFS forums, I've quickly grown to appreciate the expertise of fellow C# MVP, Tomas Petricek.

If I've forgotten any important resource links for F#, feel free to list them in the comments.

posted on Wednesday, October 31, 2007 8:18:07 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1]

kick it on DotNetKicks.com
Alan Stevens: "So far, Twitter is like hanging out in the speakers' lounge. Meaningless chatter from smart people."

My Wife: "It's like passing notes in high school. ('Social studies is SOOO boring!')"

posted on Wednesday, October 31, 2007 6:58:51 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com
 Friday, October 26, 2007
Lately, I've been spending some quality time with Microsoft's F# language. So far, I'm completely enamored with the brevity and clarity of the language. It just feels right to me.

I recently wrote up some articles on how one might use currying, partial application and function composition along with C# and delegates to produce the factorial function from two higher-order functions. The result of this labor is below.

static void Main()
{
  var reduce = HigherOrder.GetReduce<Int64>().Curry();
  var getProduct = reduce((x, y) => x * y)(1);

  var sequence = HigherOrder.GetSequence<Int64>().Curry();
  var naturalsFromOne = sequence(x => ++x)(1);

  var equals = HigherOrder.GetEquals<Int64>().Curry();

  var naturalsFromOneToX = HigherOrder.Compose(equals, naturalsFromOne);
  var factorial = HigherOrder.Compose(naturalsFromOneToX, getProduct);

  var factorialOf10 = factorial(10);

  Console.WriteLine("Factorial of 10 is {0:#,#}", factorialOf10);
}

That code is a truly magnificent beast. While it's academically interesting to torture delegates like this, it isn't all that fruitful when the language (i.e. C#, VB) doesn't really support these shenanigans. Try that in some production code and see how quickly you lose your development job.

As an exercise, here's how I might build factorial using the same techniques in F#:

#light

let getProduct = Seq.fold ( * ) 1
let naturalsFromOneToX n = [1 .. n]
let factorial = naturalsFromOneToX >> getProduct

printf "Factorial of 10 is %i" (factorial 10)

The first thing I should point out is that no delegates are used in this sample. F# natively supports functions as values so it's unnecessary to create delegates for them (and no, it doesn't create delegates under the covers). Secondly, functions are automatically curried in F#. You can declare functions so that they aren't curried, but that's really only useful if you're writing code that should be callable from other .NET languages. And finally, F# provides an operator (>>) for function composition.

To be fair, I should point out that the above implementation is pretty naive. It's not necessary to use function composition. This will suffice:

#light

let factorial n = Seq.fold ( * ) 1 [1 .. n]

printf "Factorial of 10 is %i" (factorial 10)

If compiled with fsc.exe, that code will print the following to the console:

Factorial of 10 is 3628800

That's great, but what if I try to calculate the factorial of 1000?

Factorial of 1000 is 0

Hmmm... what's going on here? Well, it turns out that the F# compiler inferred the type of "factorial" to be:

val factorial : int -> int

"int" maps to the standard .NET type, System.Int32, so this factorial function expects an Int32 and returns an Int32. However, Int32 isn't actually large enough to hold the factorial of 1000. This is a job for F#'s "bigint" type. "bigint" maps to the Microsoft.FSharp.Math.Types.BigInt type which can represent arbitrarily large integer values. With a few minor modifications, the factorial function can use "bigint," and the factorial of 1000 can be properly calculated.

#light

let factorial n = Seq.fold ( * ) 1I [1I .. n]

printf "Factorial of 1000 is %A" (factorial 1000I)

Now, the F# compiler infers the type of "factorial" to be:

val factorial : bigint -> bigint

And what does that program print to the console?

Factorial of 1000 is 40238726007709377354370243392300398571937486421071463254379
99104299385123986290205920442084869694048004799886101971960586316668729948085589
01323829669944590997424504087073759918823627727188732519779505950995276120874975
46249704360141827809464649629105639388743788648733711918104582578364784997701247
66328898359557354325131853239584630755574091142624174743493475534286465766116677
97396668820291207379143853719588249808126867838374559731746136085379534524221586
59320192809087829730843139284440328123155861103697680135730421616874760967587134
83120254785893207671691324484262361314125087802080002616831510273418279777047846
35868170164365024153691398281264810213092761244896359928705114964975419909342221
56683257208082133318611681155361583654698404670897560290095053761647584772842188
96796462449451607653534081989013854424879849599533191017233555566021394503997362
80750137837615307127761926849034352625200015888535147331611702103968175921510907
78801939317811419454525722386554146106289218796022383897147608850627686296714667
46975629112340824392081601537808898939645182632436716167621791689097799119037540
31274622289988005195444414282012187361745992642956581746628302955570299024324153
18161721046583203678690611726015878352075151628422554026517048330422614397428693
30616908979684825901254583271682264580665267699586526822728070757813918581788896
52208164348344825993266043367660176999612831860788386150279465955131156552036093
98818061213855860030143569452722420634463179746059468257310379008402443243846565
72450144028218852524709351906209290231364932734975655139587205596542287497740114
13346962715422845862377387538230483865688976461927383814900140767310446640259899
49022222176590433990188601856652648506179970235619389701786004081188972991831102
11712298459016419210688843871218556461249607987229085192968193723886426148396573
82291123125024186649353143970137428531926649875337218940694281434118520158014123
34482801505139969429015348307764456909907315243327828826986460278986432113908350
62170950025973898635542771967428222487575867657523442202075736305694988250879689
28162753848863396909959826280956121450994871701244516461260379029309120889086942
02851064018215439945715680594187274899809425474217358240106367740459574178516082
92301353580818400969963725242305608559037006242712434169090041536901059339838357
77939410970027753472000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000I

Awesome.

One last point: writing factorial in F# is completely unnecessary. It already exists.

#light

open Microsoft.FSharp.Math.BigInt

printf "Factorial of 1000 is %A" (factorial 1000I)
posted on Friday, October 26, 2007 12:02:36 PM (Pacific Standard Time, UTC-08:00)  #    Comments [3]

kick it on DotNetKicks.com
 Thursday, October 25, 2007
Back in June, Scott Hanselman and Jeff Atwood embarked on a journey to create the "Ultimate Developer Rig." I followed this with interest because I currently use a laptop for development. The laptop is convenient because I do a reasonable amount of traveling. However, recently I've found myself craving something with more horsepower and am giving serious consideration to moving my main development to a desktop and syncing the laptop for travel.

Without consulting my trophy wife, I decided to check out NewEgg to see what the components of the Ultimate Developer Rig are down to, price-wise. Here's what I found:

Component Old Price New Price
Antec P182 Gun Metal Black 0.8mm cold rolled steel ATX Mid Tower Computer Case - Retail $154.99 $139.99
MSI P6N SLI Platinum LGA 775 NVIDIA nForce 650i SLI ATX Intel Motherboard - Retail $144.99 $139.99
MSI NX8600GTS-T2D256E-OC GeForce 8600GTS 256MB 128-bit GDDR3 PCI Express x16 HDCP Ready SLI Supported Video Card - Retail $337.98 $299.98
Western Digital Raptor WD1500ADFD 150GB 10,000 RPM Serial ATA150 Hard Drive - OEM $199.99 $179.99
Seagate Barracuda 7200.10 ST3500630AS 500GB 7200 RPM SATA 3.0Gb/s Hard Drive - OEM $119.99 $119.99
Intel Core 2 Quad Q6600 Kentsfield 2.4GHz LGA 775 Processor Model BX80562Q6600 - Retail $531.90 $279.99
Scythe SCMN-1100 100mm Sleeve CPU Cooler - Retail $32.99 $32.99
CORSAIR CMPSU-520HX ATX12V v2.2 and EPS12V 2.91 520W Power Supply - Retail $129.99 $119.99
Kingston ValueRAM 2GB (2 x 1GB) 240-Pin DDR2 SDRAM DDR2 800 (PC2 6400) Dual Channel Kit Desktop Memory Model KVR800D2N5K2/2G - Retail $216.98 $157.98
LITE-ON 20X DVD±R DVD Burner with 12X DVD-RAM write and LightScribe Technology Black E-IDE/ATAPI Model LH-20A1H-185 - OEM $33.99 $32.99
  $1,903.79 $1,503.88

I'm absolutely blown away. I mean, we're talking about a price difference of nearly $400. That leaves room for a few choice upgrades like moving to 8GB of ram. All that I have to do now is get my trophy wife to sign off on it.

posted on Thursday, October 25, 2007 9:52:20 AM (Pacific Standard Time, UTC-08:00)  #    Comments [5]

kick it on DotNetKicks.com
 Wednesday, October 24, 2007
Today, I got an email from Keith Elder calling me out for not being on Twitter:
FYI, you are no longer cool :)

Email from Elder

Normally, I would swim through boiling lava to remain among "the cool" (even if only in my own mind), but it didn't come to that. Signing up was mind-numbingly easy. Follow me: dcampbell.

Thanks to The Elder and The Follas for keeping me cool.

posted on Wednesday, October 24, 2007 11:33:43 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]

kick it on DotNetKicks.com