<?xml version="1.0" encoding="utf-8"?><rss version="2.0"><channel><title>IanG on Tap</title><link>http://www.interact-sw.co.uk/iangblog/</link><description>Ian Griffiths in Weblog Form</description><copyright>(C) 2004 I D Griffiths</copyright><lastBuildDate>Sun, 08 Aug 2010 17:19:16 GMT</lastBuildDate><generator>Interact Blogger</generator><managingEditor>ian@interact-sw.co.uk</managingEditor><webMaster>ian@interact-sw.co.uk</webMaster><item><title>Cartesian Products Closing Thoughts</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6</guid><link>http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6</link><pubDate>Sun, 08 Aug 2010 17:17:14 GMT</pubDate><description>&lt;p&gt;This is the final part of a series of six blogs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1"&gt;Simple but Too Specialized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2"&gt;Moving Away from Anonymous Types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3"&gt;LINQ to LINQ&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4"&gt;The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5"&gt;Other Languages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Closing Thoughts (this entry)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Part 6 – Closing Thoughts&lt;/h3&gt;
&lt;p&gt;Back at the start of this series, I started with a simple, specialized Cartesian product where I knew the number of sets in advance. Anonymous types made this easy, but I had to move away from those to get a more general-purpose solution. This seems to happen quite a lot with anonymous types—they’re handy for very well-contained scenarios, but I often find myself getting rid of them as my code grows more complicated.&lt;/p&gt;
&lt;p&gt;I think this is an example of a broader issue. LINQ works really well in monolithic applications—if you can get everything you need in a single method, or better yet a single query, it does a great deal of very useful work for you. But as soon as you want to start splitting things up, life gets harder. You might want to reuse parts of a query, or perhaps you just want to decompose your code into smaller chunks to improve readability, testability, and maintainability. Either way, dismantling a LINQ query into its component parts is possible, but rarely straightforward. I saw a similar step up in complexity here—I started with something that was easy, using small, specialized LINQ queries, but generalizing it was a lot more work.&lt;/p&gt;
&lt;p&gt;However, although the general solution was significantly less convenient than the specialized one, it was still reasonably compact. I had been expecting to see a bigger difference between the C# code and the examples from geekier languages such as Clojure, F# and Haskell. But the results are surprisingly similar, I think. The biggest difference I can see is that Haskell’s type system makes it easier to define functions capable of operating over any monadic type—the examples for all other languages only work on lists.&lt;/p&gt;
&lt;p&gt;The next biggest difference is that the C# code has more explicit typing—I’ve had to say a lot about the argument and return types of the &lt;code&gt;CartesianProduct&lt;/code&gt; method. You’re allowed to state this stuff explicitly in Haskell if you want, but you’re not required to. This brings me onto my final point: ceremony.&lt;/p&gt;
&lt;h3&gt;An Unfashionable Defence of Ceremony&lt;/h3&gt;
&lt;p&gt;It has recently become fashionable to attack some languages for requiring more “ceremony” than others. Apparently, “ceremony” is anything you have to write because it's formally required, but which doesn’t directly say anything about what your program does. The need for explicit type declarations in C# is one example. With Haskell I was able to write just the essence, whereas with C#, I had to say more about what I was doing before I could do it. (Haskell is very much a statically typed language, by the way. It’s just that you can leave its type inference system to do a lot of the work.)&lt;/p&gt;
&lt;p&gt;I hold an unfashionable view: I’m not convinced that absence of ceremony is intrinsically a good thing—in this particular case I suspect it makes it easier for someone reading the code. I don’t want to have to perform complicated type inference in my head when reading source code—I’d rather the code was explicit about the types it’s using because a) that saves time when I’m reading it and b) removes doubt over whether the author wrote what he or she meant to write.&lt;/p&gt;
&lt;p&gt;In what little Haskell I’ve done, I’ve found it much easier to write explicit type declarations even in cases where the compiler doesn’t need them. The ceremony’s not for the compiler—it’s for my benefit. Just to be clear: I don't think that ceremony is intrinsically good either. Pointless verbosity helps nobody. I’m just saying that sometimes, making things explicit can improve readability.&lt;/p&gt;</description></item><item><title>Other Languages</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5</guid><link>http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5</link><pubDate>Thu, 05 Aug 2010 22:33:19 GMT</pubDate><description>&lt;p&gt;This is part five in a series of blogs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1"&gt;Simple but Too Specialized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2"&gt;Moving Away from Anonymous Types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3"&gt;LINQ to LINQ&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4"&gt;The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Other Languages (this entry)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6"&gt;Closing Thoughts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Part 5 – Other Languages&lt;/h3&gt;
&lt;p&gt;In the previous blogs in this series, I’ve shown how to generate Cartesian products in C#. I started with the simple, elegant, anonymous type solution that works when you know at compile time exactly what your inputs are. But because my original scenario involved varying inputs, I built a more generalized solution, and then honed it to the point where I was reasonably happy with its size and readability.&lt;/p&gt;
&lt;p&gt;In this part, I thought it’d be interesting to show solutions in a handful of other languages. In language advocacy fist fights^H^H^H^H^H^H^H^H^H^H^H debates, it’s common to argue that a language’s power is inversely proportional to the amount of code required to express a particular concept. In other words less is more—the language that can solve a particular problem in the smallest space wins. (I don’t completely agree with that—I think readability matters, and terseness is sometimes the enemy of readability. But size has the benefit of being objective.)&lt;/p&gt;
&lt;p&gt;Haskell offers the shortest solution I’ve seen to this problem:&lt;/p&gt;
&lt;pre&gt;sequence [['1', '2'], ['A', 'B']]
&lt;/pre&gt;
&lt;p&gt;This produces:&lt;/p&gt;
&lt;pre&gt;["1A","1B","2A","2B"]
&lt;/pre&gt;
&lt;p&gt;That initially struck me as a little wierd until I realised that a string in Haskell is just a list of characters. I think it makes slightly more sense to think of that output as this:&lt;/p&gt;
&lt;pre&gt;[['1','A'],['1','B'],['2', 'A'],['2','B']]
&lt;/pre&gt;
&lt;p&gt;That makes it more obvious that &lt;code&gt;sequence&lt;/code&gt; has just produced every possible concatenation. But Haskell prefers to print lists of characters using string literal syntax. In fact if you type in the second representation at a Haskell prompt, it'll print out the first one.&lt;/p&gt;
&lt;p&gt;You might think that this is cheating because I appear to be using a built-in function to do the job. But that would be a bad argument on two counts. First, the expressiveness of the available library functions is a critically important aspect of the practical usefulness of any language. Second, this built-in &lt;a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html"&gt;&lt;code&gt;sequence&lt;/code&gt;&lt;/a&gt; function is not just for Cartesian products—it’s more general-purpose. What you’re looking at in that example is a very general mechanism being applied in this particular case to produce an n-ary Cartesian product.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;sequence&lt;/code&gt; function works with any monadic type. For example, I can use Haskell’s &lt;code&gt;Maybe&lt;/code&gt; monad, which is roughly analogous to the idea of a nullable type:&lt;/p&gt;
&lt;pre&gt;sequence [Just 1, Just 2, Just 3]
&lt;/pre&gt;
&lt;p&gt;Here I’m passing a list of maybes where every item does in fact have a value, and it produces:&lt;/p&gt;
&lt;pre&gt;Just [1,2,3]
&lt;/pre&gt;
&lt;p&gt;But if I include &lt;code&gt;Nothing&lt;/code&gt;, which is (sort of) analogous to null, then the usual behaviour of the &lt;code&gt;Maybe&lt;/code&gt; monad kicks in, which is to say I get &lt;code&gt;N&lt;/code&gt;&lt;code&gt;othing&lt;/code&gt; out. So this:&lt;/p&gt;
&lt;pre&gt;sequence [Just 1, Just 2, Nothing, Just 3]
&lt;/pre&gt;
&lt;p&gt;produces this:&lt;/p&gt;
&lt;pre&gt;Nothing
&lt;/pre&gt;
&lt;p&gt;Haskell also uses monads to handle IO, so I could use &lt;code&gt;sequence&lt;/code&gt; to execute a series of IO actions:&lt;/p&gt;
&lt;pre&gt;get2chars = sequence [getChar, getChar]
&lt;/pre&gt;
&lt;p&gt;The &lt;a href="http://haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/System-IO.html"&gt;getChar&lt;/a&gt; function returns an &lt;code&gt;IO Char&lt;/code&gt;, so passing a list of these into &lt;code&gt;sequence&lt;/code&gt; produces something of type &lt;code&gt;IO [Char]&lt;/code&gt;, i.e., it produces an IO monad which can feed a list of &lt;code&gt;Char&lt;/code&gt; values into a subsequent step:&lt;/p&gt;
&lt;pre&gt;do { result &amp;lt;- ioseq; putStrLn result }
&lt;/pre&gt;
&lt;p&gt;That reads two characters, and then prints them to the output. Not a particularly useful example perhaps, but it illustrates that the way in which the &lt;code&gt;sequence&lt;/code&gt; function combines the elements is defined not by &lt;code&gt;sequence&lt;/code&gt; itself, but by the monad you’re using.&lt;/p&gt;
&lt;p&gt;If you’re not entirely familiar with monads, and want to understand this in terms more familiar to a C# developer, you could think of Haskell’s &lt;code&gt;sequence&lt;/code&gt; function as being the generalized version of the &lt;code&gt;CartesianProduct&lt;/code&gt; function I wrote earlier, but rather than being specific to &lt;code&gt;IEnumerable&lt;/code&gt;&lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; CartesianProduct&amp;lt;T&amp;gt;(
    &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; inputs)
&lt;/pre&gt;
&lt;p&gt;it works for any type that provides the LINQ &lt;code&gt;SelectMany&lt;/code&gt; operator. (So a hypothetical C# equivalent of &lt;code&gt;sequence&lt;/code&gt; would work against LINQ to XML or LINQ to Entities, and not just LINQ to Objects, which is what our current &lt;code&gt;CartesianProduct&lt;/code&gt; implementation uses.) &lt;code&gt;SelectMany&lt;/code&gt; is just LINQ’s name for one of the standard monadic operators. (It’s sometimes called “bind”, and Haskell denotes it with the &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; operator.) So you could imagine this sort of thing:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IMonad&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; Sequence&amp;lt;T&amp;gt;(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IMonad&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; inputs)
&lt;/pre&gt;
&lt;p&gt;That’s not real because there is no &lt;code&gt;IMonad&lt;/code&gt;&lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; in .NET—I’m just trying to illustrate the broad idea behind Haskell’s &lt;code&gt;sequence&lt;/code&gt; function. So the reason we can use &lt;code&gt;sequence&lt;/code&gt; to build an n-ary Cartesian product is the same reason we can build them with C# LINQ queries with multiple &lt;code&gt;from&lt;/code&gt; clauses—both C# and Haskell represent lists as monadic types whose binding behaviour happens to be a Cartesian product. C# doesn’t explicitly call these things monads, but it’s the same idea in practice.&lt;/p&gt;
&lt;p&gt;(Note that &lt;code&gt;sequence&lt;/code&gt; has one limitation that my C# code doesn't: Haskell has no direct equivalent of &lt;code&gt;System.Object&lt;/code&gt;. The C# method can combine any old mixture of types, whereas Haskell's a bit more picky. As it happens, I don't care for my original problem: I only needed to cope with the number of input sets being unknown at compile time. The set members all happened to be of the same type; the ability to cope with a mixture of types was an accidental bonus, and not even one I wanted to keep. As you will recall, I eventually moved from &lt;code&gt;object&lt;/code&gt; to a type argument. But if you really wanted to handle a mixture of types not known until runtime, Haskell's actually at a disadvantage; or perhaps the idiomatic Haskell response would be to wave my hand in the manner of a Jedi and tell you that this is not the type system you're looking for. In practice, I suspect that if you're using Haskell, you'd probably be unlikely to find yourself in a position where you were trying to handle that unknown mixture of types anyway.)&lt;/p&gt;
&lt;p&gt;So Haskell wins because it has a built-in function, &lt;code&gt;sequence&lt;/code&gt;, which combines a list of monadic types. I had to write my own function to do that in C#. But if Haskell didn’t have &lt;code&gt;sequence&lt;/code&gt;, I could build it in much the same way I did with C#. In C# I used the &lt;code&gt;Aggregate&lt;/code&gt; operator, and in Haskell I could use the similar &lt;code&gt;foldr&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;mySequence = foldr
  (\ input soFar -&amp;gt;
    soFar &amp;gt;&amp;gt;= (\prevProductItem -&amp;gt;
      input &amp;gt;&amp;gt;= (\item -&amp;gt; [item:prevProductItem])))
  [[]]
&lt;/pre&gt;
&lt;p&gt;Although that works here, it’s a little too specialized—I’m constructing lists with the [] syntax here, and the original &lt;code&gt;sequence&lt;/code&gt; function works with any monad. Fortunately, as mentioned earlier, Haskell requires monadic types to define an operation to construct an instance of the monad from a value. (The gap I filled in C# with my &lt;code&gt;EnumerableFrom&lt;/code&gt; method in the previous part. And as I noted in a recent update to the previous article, &lt;a href="http://msdn.microsoft.com/devlabs/ee794896"&gt;Rx&lt;/a&gt; provides something similar through its &lt;a href="http://rxwiki.wikidot.com/enumerableex-return"&gt;&lt;code&gt;EnumerableEx.return&lt;/code&gt;&lt;/a&gt; method.) This is provided by the &lt;code&gt;return&lt;/code&gt; operation:&lt;/p&gt;
&lt;pre&gt;mySequence = foldr
  (\ input soFar -&amp;gt;
    soFar &amp;gt;&amp;gt;= (\prevProductItem -&amp;gt;
      input &amp;gt;&amp;gt;= (\item -&amp;gt; return (item:prevProductItem))))
  (return [])
&lt;/pre&gt;
&lt;p&gt;It might not be obvious if you’re unfamiliar with Haskell, but the structure’s pretty similar to the C# version. The &lt;code&gt;from&lt;/code&gt; clauses have turned into &lt;code&gt;&amp;gt;&amp;gt;=&lt;/code&gt; operators, the call to &lt;code&gt;Append&lt;/code&gt; has been replaced with the colon operator. And in fact that’s a prepend, rather than an append; everything’s turned inside out because &lt;code&gt;foldr&lt;/code&gt; works from back to front… (I could have used &lt;code&gt;foldl&lt;/code&gt;, but &lt;code&gt;foldr&lt;/code&gt; seems to be the more common idiom in Haskell.)&lt;/p&gt;
&lt;p&gt;Haskell offers a specialized syntax for chaining monads together: the &lt;code&gt;do&lt;/code&gt; notation. The following example is equivalent to the preceding one, but it might be more idiomatically correct:&lt;/p&gt;
&lt;pre&gt;mySequence = foldr
  (\ input soFar -&amp;gt;
      do prevProductItem &amp;lt;- soFar
         item &amp;lt;- input
         return (item:prevProductItem))
  (return [])
&lt;/pre&gt;
&lt;p&gt;Hopefully this makes the structural similarity between this Haskell example and the C# CartesianProduct slightly more obvious—compare the &lt;code&gt;&amp;lt;-&lt;/code&gt; clauses in this &lt;code&gt;do&lt;/code&gt; notation with the &lt;code&gt;from&lt;/code&gt; clauses in the C#. (Compared to &lt;code&gt;foldr&lt;/code&gt;, LINQ’s &lt;code&gt;Aggregate&lt;/code&gt; happens to use the reverse order for its arguments, and also for the arguments for the lambda, but otherwise, this is pretty similar.)&lt;/p&gt;
&lt;p&gt;This still relies on monadic operators, so just as C# &lt;code&gt;from&lt;/code&gt; clauses work with any type that offers the relevant LINQ operators, all the Haskell examples shown so far will work with any monad. And when I feed in a list of lists, it’s the Haskell List monad that’s doing the actual work of producing the cross product here, just as the C# code ultimately relies on the LINQ to Objects code in the &lt;a href="http://msdn.microsoft.com/library/system.linq.enumerable"&gt;Enumerable&lt;/a&gt; class. If you prefer your code more explicit, here’s one that generates the products without relying on monads:&lt;/p&gt;
&lt;pre&gt;explicitCartes = foldr
  (\ input soFar -&amp;gt;
    concatMap (\prevProductItem -&amp;gt;
      concatMap (\item -&amp;gt; [item:prevProductItem]) input)
      soFar)
  [[]]
&lt;/pre&gt;
&lt;p&gt;Here’s a completely different take on the same problem:&lt;/p&gt;
&lt;pre&gt;compCartes = foldr
  (\ input soFar -&amp;gt;
    [item:prevProductItem | prevProductItem &amp;lt;- soFar, item &amp;lt;- input])
  [[]]
&lt;/pre&gt;
&lt;p&gt;That’s using a list comprehension. Here I’m essentially exploiting the fact that the language will generate a 2-set Cartesian product if I define a list in terms of two input sets, and once again I’m using &lt;code&gt;foldr&lt;/code&gt; to generalise that to an n-ary cross product. (This last example only works with lists—unlike the built-in &lt;code&gt;sequence&lt;/code&gt;, and the last two &lt;code&gt;mySequence&lt;/code&gt; examples above, this won’t work with other monads.)&lt;/p&gt;
&lt;p&gt;There are probably other viable approaches. These may not be particularly idiomatically good examples of Haskell by the way—not only do I not know much Haskell, I’ve also attempted to keep some kind of connection between my C# examples and the Haskell code through my choice of variable names, to make it easier to explore the similarities and differences.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.pluralsight-training.net/community/blogs/craig/"&gt;Craig Andera&lt;/a&gt; helpfully supplied me with a &lt;a href="http://clojure.org/"&gt;Clojure&lt;/a&gt; version:&lt;/p&gt;
&lt;pre&gt;(defn cross-prod [&amp;amp; colls]
  (-&amp;gt;&amp;gt; colls
       (reduce #(for [x %1 y %2] [x y]))
       (map flatten)))
&lt;/pre&gt;
&lt;p&gt;I’m pretty sure that’s doing much the same thing—&lt;code&gt;reduce&lt;/code&gt; is Lisp’s name for what Haskell calls &lt;code&gt;foldr&lt;/code&gt;, and what LINQ calls &lt;code&gt;Aggregate&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I also took a shot at an F# version. I don’t really know much F#, but F# MVP &lt;a href="http://richardminerich.com/"&gt;Richard Minerich&lt;/a&gt; (aka &lt;a href="http://twitter.com/rickasaurus"&gt;rickasaurus&lt;/a&gt;) generously looked at my example, and was kind enough to describe it as “quite good”. He also came up with something more clever, but it would actually have required more code, so I'm sticking with my original:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;let&lt;/span&gt; cartes inputs =
  List.foldBack
    (&lt;span style="color:blue"&gt;fun&lt;/span&gt; input soFar &lt;span style="color:blue"&gt;-&amp;gt;&lt;/span&gt; seq { &lt;span style="color:blue"&gt;for&lt;/span&gt; y &lt;span style="color:blue"&gt;in&lt;/span&gt; soFar &lt;span style="color:blue"&gt;do&lt;/span&gt; &lt;span style="color:blue"&gt;for&lt;/span&gt; x &lt;span style="color:blue"&gt;in&lt;/span&gt; input &lt;span style="color:blue"&gt;do&lt;/span&gt; &lt;span style="color:blue"&gt;yield&lt;/span&gt; x::y })
    inputs
    (Seq.singleton List.Empty)

&lt;span style="color:blue"&gt;let&lt;/span&gt; result = cartes [[1..5];[42;50];[99;100]] |&amp;gt; Seq.toArray
&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;List.foldBack&lt;/code&gt; operation is similar to Haskell’s &lt;code&gt;foldr&lt;/code&gt;, and again, the overall structure is much the same as the C# example. Don’t be thrown by the name &lt;code&gt;seq&lt;/code&gt;—this is different from Haskell’s &lt;code&gt;sequence&lt;/code&gt; function. In F#, the &lt;code&gt;seq&lt;/code&gt; keyword is used to introduce a block of code that will produce a sequence of items as its output. The block that follows here is conceptually pretty similar to the C# example, but with a pair of &lt;code&gt;for … in … do&lt;/code&gt; constructs in place of a pair of &lt;code&gt;from&lt;/code&gt; clauses.&lt;/p&gt;
&lt;p&gt;(Note that as with the Haskell version, this one’s also picky about types. But again it doesn’t matter to me, because in my original problem, the input sets all contained members of the same type. It was only the number of sets I didn't know at compile time.)&lt;/p&gt;
&lt;p&gt;The final line of this F# example is just for test purposes, and the reason I’m feeding the result through the &lt;code&gt;Seq.toArray&lt;/code&gt; function is that the debugger shows more useful information for arrays than it does for generic sequences. (I guess that’s because a sequence might be infinite, so attempting to display the whole thing might be undesirable. But in converting it to an array, I’ve already chosen to force the sequence to be fully evaluated, so the debugger can show it safely.) Here’s the output from evaluating that last line in the F# Interactive window:&lt;/p&gt;
&lt;pre&gt;val result : int list array =
  [|[1; 42; 99]; [2; 42; 99]; [3; 42; 99]; [4; 42; 99]; [5; 42; 99];
    [1; 50; 99]; [2; 50; 99]; [3; 50; 99]; [4; 50; 99]; [5; 50; 99];
    [1; 42; 100]; [2; 42; 100]; [3; 42; 100]; [4; 42; 100]; [5; 42; 100];
    [1; 50; 100]; [2; 50; 100]; [3; 50; 100]; [4; 50; 100]; [5; 50; 100]|]
&lt;/pre&gt;
&lt;p&gt;So that seems to work.&lt;/p&gt;
&lt;h3&gt;Old School&lt;/h3&gt;
&lt;p&gt;I asked a friend who works mainly in Java for a Java version of this code. I’m not going to offer any commentary beyond observing that a) this is probably roughly what it would have look like in C# before C# 3.0 turned up and b) this is why I like C# 3.0 so much:&lt;/p&gt;
&lt;pre&gt;import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


public class Cartesian {
    public static void main(final String... args) {

         final Object[] letters = { 'A', 'B', 'C' };
         final Object[] numbers = { 1, 2, 3, 4 };
         final Object[] colours = { "Red", "Blue" };

         final List&amp;lt;List&amp;lt;Object&amp;gt;&amp;gt; params = new ArrayList&amp;lt;List&amp;lt;Object&amp;gt;&amp;gt;();
         params.add(Arrays.asList(letters));
         params.add(Arrays.asList(numbers));
         params.add(Arrays.asList(colours));

         for( final List&amp;lt;Object&amp;gt; item : cartesian(params)) {
             System.out.println(item);
        }
    }

     public static &amp;lt;T&amp;gt; List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; cartesian(final List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; params) {
         if( !(params.size() &amp;gt; 0) ) return new LinkedList&amp;lt;List&amp;lt;T&amp;gt;&amp;gt;();
         return cartesian(new LinkedList&amp;lt;List&amp;lt;T&amp;gt;&amp;gt;(params),
             new ArrayList&amp;lt;List&amp;lt;T&amp;gt;&amp;gt;());
     }

    private static &amp;lt;T&amp;gt; List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; cartesian(
      final LinkedList&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; params, final List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; results) {
         if( !(params.size() &amp;gt; 0) ) return results;
         aggregate(params.removeLast(),results);
         return cartesian(params,results);
     }

    private static &amp;lt;T&amp;gt; void aggregate(final List&amp;lt;T&amp;gt; items,
                                      final List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; target) {
        if( target.size() == 0 ) {
            for(final T item : items) {
                final List&amp;lt;T&amp;gt; targetItems = new ArrayList&amp;lt;T&amp;gt;();
                targetItems.add(item);
                target.add(targetItems);
            }
        } else {
            final List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; oldTarget = new LinkedList&amp;lt;List&amp;lt;T&amp;gt;&amp;gt;(target);
            target.clear();
            for(final T item : items) {
                for(final List&amp;lt;T&amp;gt; oldTargetItems : oldTarget) {
                    final List&amp;lt;T&amp;gt; targetItems = new ArrayList&amp;lt;T&amp;gt;();
                    targetItems.add(item);
                    targetItems.addAll(oldTargetItems);
                    target.add(targetItems);
                }
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;Next time, some final thoughts.&lt;/p&gt;</description></item><item><title>The Missing LINQ: IEnumerable&lt;T&gt; and Scalars</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4</guid><link>http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4</link><pubDate>Mon, 02 Aug 2010 14:33:25 GMT</pubDate><description>&lt;p&gt;This is part four in a series of blogs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1"&gt;Simple but Too Specialized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2"&gt;Moving Away from Anonymous Types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3"&gt;LINQ to LINQ&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars (this entry)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5"&gt;Other Languages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6"&gt;Closing Thoughts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Part 4 – The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars&lt;/h3&gt;
&lt;p&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2"&gt;Last time&lt;/a&gt;, I turned LINQ on itself: I used a LINQ query to build a LINQ query. This worked, but the result wasn’t quite as neat as it could have been. I can improve matters by adding a couple of helpers to the world of LINQ. I’ve often found it slightly odd that these don’t seem to be built into LINQ, but they’re easily added.&lt;/p&gt;
&lt;p&gt;LINQ offers no built in clean way to take a single scalar item and convert it into a sequence with that single item in it. The usual approach is just to build a single-element array. This works, but it's rather clunky, and I often run into situations where this curious omission makes code more awkward than it needs to be. It has led to a rather ugly first argument to &lt;code&gt;Aggregate&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;        (&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;) &lt;span style="color:blue"&gt;new&lt;/span&gt; T[][] { &lt;span style="color:blue"&gt;new&lt;/span&gt; T[0] },
&lt;/pre&gt;
&lt;p&gt;What I’m actually saying here is that I want to take an single element—an empty sequence of T (&lt;code&gt;new &lt;/code&gt;&lt;code&gt;T[&lt;/code&gt;&lt;code&gt;0]&lt;/code&gt;)—and turn it into a sequence that contains just that one element. (I’m building a sequence of sequences here, remember.) The &lt;code&gt;Enumerable&lt;/code&gt; class does actually provide a helper for building an empty sequence, so I can make this code say what it does slightly better by writing this:&lt;/p&gt;
&lt;pre&gt;(&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;) &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;[] { &lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Empty&amp;lt;T&amp;gt;() },
&lt;/pre&gt;
&lt;p&gt;I think it’s now slightly more obvious that an empty sequence is involved here. But I’ve ended up building an array to get my one-element sequence, and I think it’s ugly. What really I’d like to write is this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.From(&lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Empty&amp;lt;T&amp;gt;()),
&lt;/pre&gt;
&lt;p&gt;I’m imagining a &lt;code&gt;From&lt;/code&gt; method here that returns a single-element sequence containing whatever element you pass as the argument. Sadly, this method doesn’t appear to exist. That seems weird to me—we have the &lt;code&gt;Empty&amp;lt;T&amp;gt;&lt;/code&gt; method, so it would seem natural also to have a method that wraps a single item as an enumerable. (Moreover, LINQ draws heavily from the concepts behind monadic types such as those offered in Haskell. One of the fundamental operations of a monad is the ability to construct one from any underlying type. There are only two fundamental operations, so this is a particularly striking omission.) It’s easy enough to write our own though:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;private&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; EnumerableFrom&amp;lt;T&amp;gt;(T item)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; T[] { item };
}
&lt;/pre&gt;
&lt;p&gt;Other implementations are possible of course—this might be a more expressive idiom:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;private&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; EnumerableFrom&amp;lt;T&amp;gt;(T item)
{
    &lt;span style="color:blue"&gt;yield&lt;/span&gt; &lt;span style="color:blue"&gt;return&lt;/span&gt; item;
}
&lt;/pre&gt;
&lt;p&gt;That’s prettier, and appeals much more to my language geek tendencies, but it generates a lot more code under the covers. So I’ll stick with the first one.&lt;/p&gt;
&lt;p&gt;A similar problem exists with concatenation. On this line here:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(&lt;span style="color:blue"&gt;new&lt;/span&gt; T[] { item }));
&lt;/pre&gt;
&lt;p&gt;I have an &lt;code&gt;IEnumerable&lt;/code&gt;&lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; (&lt;code&gt;prevProductItem&lt;/code&gt;), and a single value of type &lt;code&gt;T&lt;/code&gt; (&lt;code&gt;item&lt;/code&gt;), and I want to append that to the original enumeration. The Concat operator is only able to combine two enumerations, so I’m obliged to turn that single item into a sequence by wrapping it in an array. This is essentially another instance of the previous problem, so I could just use my new &lt;code&gt;EnumerableFrom&lt;/code&gt; method:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(EnumerableFrom(item)));
&lt;/pre&gt;
&lt;p&gt;But that feels a bit heavy handed. I’d love it if there were an overload of &lt;code&gt;Concat&lt;/code&gt; that accepted singular values, in which case I could write:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(item); &lt;span style="color:green"&gt;// Won't compile&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Although that might cause ambiguity, so perhaps it’d be better to have a distinct operator for appending just one item:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Append(item)); &lt;span style="color:green"&gt;// Won't compile without help&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;As far as I can tell, that doesn’t exist. (Although it’s always possible that it does exist under a less obvious name, and I’ve simply missed it. Wouldn’t be the first time…) But I can write an extension method to provide it:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:blue"&gt;class&lt;/span&gt; &lt;span style="color:dimgray"&gt;AppendExtension&lt;/span&gt;
{
    &lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Append&amp;lt;T&amp;gt;(&lt;span style="color:blue"&gt;this&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; that, T item)
    {
        &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; itemAsSequence = &lt;span style="color:blue"&gt;new&lt;/span&gt; T[] { item };
        &lt;span style="color:blue"&gt;return&lt;/span&gt; that.Concat(itemAsSequence);
    }
}
&lt;/pre&gt;
&lt;p&gt;With this and my &lt;code&gt;EnumerableFrom&lt;/code&gt; helper method in place, I can simplify our &lt;code&gt;CartesianProduct&lt;/code&gt; method a little:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; CartesianProduct&amp;lt;T&amp;gt;(
    &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; inputs)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; inputs.Aggregate(
        EnumerableFrom(&lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Empty&amp;lt;T&amp;gt;()),
        (soFar, input) =&amp;gt;
            &lt;span style="color:blue"&gt;from&lt;/span&gt; prevProductItem &lt;span style="color:blue"&gt;in&lt;/span&gt; soFar
            &lt;span style="color:blue"&gt;from&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; input
            &lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Append(item));
}
&lt;/pre&gt;
&lt;p&gt;That’s looking a lot calmer to me.&lt;/p&gt;
&lt;p&gt;I fear it may be write-only code—I’m not convinced that if I were to come across that finished product 6 months after writing it that I’d be able to work out how it works without first referring back to this blog series… However, because I know what an n-ary Cartesian product is, I’ll find it pretty easy to read code that &lt;i&gt;uses&lt;/i&gt; this method.&lt;/p&gt;
&lt;p&gt;Next time we’ll look at some solutions to this problem in other programming languages, to see how C# compares.&lt;/p&gt;
&lt;p&gt;[&lt;b&gt;Update, 5th August 2010:&lt;/b&gt; A few people have emailed me to mention that the &lt;a href="http://msdn.microsoft.com/devlabs/ee794896"&gt;Reactive Extensions for .NET (Rx)&lt;/a&gt; offer the missing features I add. So if these ever make it out of the labs into the full .NET Framework, I'll get my wish. The monad influence is clear - they've given their version of what I called EnumerableFrom the name &lt;a href="http://rxwiki.wikidot.com/enumerableex-return"&gt;return&lt;/a&gt; (yes, that's a blank web page - there doesn't seem to be much online documentation, and that's the only reference I could find - you'll need to download Rx to see the actual docs). Haskell also calls it return.]&lt;/p&gt;</description></item><item><title>LINQ to LINQ</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3</guid><link>http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3</link><pubDate>Sun, 01 Aug 2010 18:27:13 GMT</pubDate><description>&lt;p&gt;This is part three in a series of blogs.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1"&gt;Simple but Too Specialized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2"&gt;Moving Away from Anonymous Types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;LINQ to LINQ (this entry)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4"&gt;The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5"&gt;Other Languages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6"&gt;Closing Thoughts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Part 3 – LINQ to LINQ&lt;/h3&gt;
&lt;p&gt;Last time, I wrote a generalized method that built an n-ary Cartesian Product. It did this by building up a LINQ query—it chained as many &lt;code&gt;SelectMany&lt;/code&gt; calls together as were needed. But it turns out that I am reinventing the wheel here—this is an example of a slightly more general process. Our n-ary Cartesian product method works by taking a starting value (a sequence containing the empty set), and repeatedly applying a function (&lt;code&gt;SelectMany&lt;/code&gt;) once for each item in an input sequence (the sequence of input sets we’re combining), feeding the output of each step back in as the input to the next.&lt;/p&gt;
&lt;p&gt;If the LINQ team had employed Apple’s marketing agency, this might be a good time to say: there’s an operator for that!&lt;/p&gt;
&lt;p&gt;This concept of building up something by repeatedly applying the output of a function as the input to the same function is quite a common one. The process of calculating the sum of a list of numbers has exactly the same structure: your initial value is zero, and then for each number in the input list, you apply the ‘+’ (addition) function to the running total and the current number. It’s the same process, but using numbers and addition instead of sequences and &lt;code&gt;SelectMany&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Most list processing systems have some general-purpose implementation of this process, and it goes by various names, including fold and reduce. And in LINQ it’s called Aggregate. Here’s a modified version of the method, using the LINQ Aggregate operator:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt; CartesianProduct(&lt;span style="color:blue"&gt;params&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] inputs)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; inputs.Aggregate(
        (&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt;) &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] { &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[0] },
        (soFar, input) =&amp;gt; soFar.SelectMany(prevProductItem =&amp;gt;
            &lt;span style="color:blue"&gt;from&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; input
            &lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(&lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[] { item }).ToArray()));
}
&lt;/pre&gt;
&lt;p&gt;Earlier, I turned my LINQ query expression into explicit calls to &lt;code&gt;SelectMany&lt;/code&gt;, but that was just an illustrative device to make it more clear what’s going on. Having got to this stage, I think it looks slightly neater to go back to the query expression syntax. It’s no less powerful in this example:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt; CartesianProduct(&lt;span style="color:blue"&gt;params&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] inputs)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; inputs.Aggregate(
        (&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt;) &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] { &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[0] },
        (soFar, input) =&amp;gt;
            &lt;span style="color:blue"&gt;from&lt;/span&gt; prevProductItem &lt;span style="color:blue"&gt;in&lt;/span&gt; soFar
            &lt;span style="color:blue"&gt;from&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; input
            &lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(&lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[] { item }).ToArray());
}
&lt;/pre&gt;
&lt;p&gt;So there’s the function that uses LINQ to build a LINQ query. Specifically, it uses the LINQ Aggregate operator to combine a series of LINQ SelectMany queries into one big query.&lt;/p&gt;
&lt;p&gt;I can now write this sort of code:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[] letters = { &lt;span style="color:brown"&gt;'A'&lt;/span&gt;, &lt;span style="color:brown"&gt;'B'&lt;/span&gt;, &lt;span style="color:brown"&gt;'C'&lt;/span&gt; };
&lt;span style="color:blue"&gt;object&lt;/span&gt;[] numbers = { 1, 2, 3, 4 };
&lt;span style="color:blue"&gt;object&lt;/span&gt;[] colours = { &lt;span style="color:brown"&gt;"Red"&lt;/span&gt;, &lt;span style="color:brown"&gt;"Blue"&lt;/span&gt; };

&lt;span style="color:blue"&gt;var&lt;/span&gt; cartesianProduct = CartesianProduct(letters, numbers, colours);
&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;var&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; cartesianProduct)
{
    &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:blue"&gt;string&lt;/span&gt;.Join(&lt;span style="color:brown"&gt;","&lt;/span&gt;, item));
}
&lt;/pre&gt;
&lt;p&gt;This code produces exactly the same output as the previous output shown, i.e., it is the Cartesian product of the three sets being fed into the method.&lt;/p&gt;
&lt;p&gt;Comparing this with the original example in &lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1"&gt;part one of this series&lt;/a&gt;, everything’s now an &lt;code&gt;object[]&lt;/code&gt;, so I’ve lost some compile time type checking, and I’ve lost meaningful names for our items, but the benefit is increased generality—I can pass as many sets as I like into the &lt;code&gt;CartesianProduct&lt;/code&gt; method. I can decide on the number of sets at runtime, which was my original requirement.&lt;/p&gt;
&lt;p&gt;Here’s a different way to use this &lt;code&gt;CartesianProduct&lt;/code&gt; method. This next example generates digits for all numbers in a particular base of a particular length. The &lt;code&gt;digitValues&lt;/code&gt; array contains all available digits in the selected base (e.g. {0, 1} for base 2), and then I use the &lt;code&gt;Enumerable.Repeat&lt;/code&gt; method to generate a sequence containing that set of digits over and over again for the specified number of digits.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt; Numbers(&lt;span style="color:blue"&gt;int&lt;/span&gt; radix, &lt;span style="color:blue"&gt;int&lt;/span&gt; digits)
{
    &lt;span style="color:blue"&gt;object&lt;/span&gt;[] digitValues = &lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Range(0, radix).Cast&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;&amp;gt;().ToArray();
    &lt;span style="color:blue"&gt;return&lt;/span&gt; CartesianProduct(&lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Repeat(digitValues, digits).ToArray());
}
&lt;/pre&gt;
&lt;p&gt;Those calls to &lt;code&gt;Cast&lt;/code&gt; and &lt;code&gt;ToArray&lt;/code&gt; are bugging me though.&lt;/p&gt;
&lt;h3&gt;Cleaning it Up&lt;/h3&gt;
&lt;p&gt;Earlier, I made a rather suspect decision—you may well have raised an eyebrow when I said I was going to represent each tuple as an array of objects. Arrays? Really? In the midst of all this LINQ, I decided to use arrays? Well actually, originally I didn’t—before I wrote this series of blogs, I started out by using enumerations for the tuples as well as for the input sets. The reason I introduced &lt;code&gt;object[]&lt;/code&gt; was to make the example slightly easier to follow—as I was working through it, I kept forgetting whether the enumeration I was looking at was the one containing the input sets, or was one of the input sets themselves, or was perhaps one of my output values…&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;object[]&lt;/code&gt; type had the useful benefit of being visually very distinct from all the other &lt;code&gt;IEnumerable&lt;/code&gt;&lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; types, making it very easy to know when I was looking at something representing a tuple in the output set. However, now that I’ve got it working, I want to get rid of it, because arrays are an unnecessarily restrictive choice here. Here’s a modified version that uses enumerables:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; CartesianProduct(
    &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; inputs)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; inputs.Aggregate(
        (&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;) &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] { &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[0] },
        (soFar, input) =&amp;gt;
            &lt;span style="color:blue"&gt;from&lt;/span&gt; prevProductItem &lt;span style="color:blue"&gt;in&lt;/span&gt; soFar
            &lt;span style="color:blue"&gt;from&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; input
            &lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(&lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[] { item }));
}
&lt;/pre&gt;
&lt;p&gt;This allows a slightly neater version of &lt;code&gt;Numbers&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt; Numbers(&lt;span style="color:blue"&gt;int&lt;/span&gt; radix, &lt;span style="color:blue"&gt;int&lt;/span&gt; digits)
{
    &lt;span style="color:blue"&gt;var&lt;/span&gt; digitValues = &lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Range(0, radix).Cast&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;&amp;gt;();
    &lt;span style="color:blue"&gt;return&lt;/span&gt; CartesianProduct(&lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Repeat(digitValues, digits));
}
&lt;/pre&gt;
&lt;p&gt;But there’s still that call to &lt;code&gt;Cast&amp;lt;object&lt;/code&gt;&lt;code&gt;&amp;gt;(&lt;/code&gt;&lt;code&gt;)&lt;/code&gt;. That’s only in there because &lt;code&gt;CartesianProduct&lt;/code&gt; is using &lt;code&gt;object&lt;/code&gt; as its representation for items in the input sets. For my first few examples, where the input sets were all of different types (&lt;code&gt;char&lt;/code&gt;, &lt;code&gt;int&lt;/code&gt;, and &lt;code&gt;string&lt;/code&gt;), that made sense, but in this case, all three sets contain members of the same type: &lt;code&gt;int&lt;/code&gt;. (And as it happens, in the program I was working on that originally motivated this blog post, all the input sets contained members of type &lt;code&gt;Action&lt;/code&gt;.) I’d like to improve this. I can parameterise &lt;code&gt;CartesianProduct&lt;/code&gt; by the type it uses to represent elements in input sets:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; CartesianProduct&amp;lt;T&amp;gt;(
    &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; inputs)
{
    &lt;span style="color:blue"&gt;return&lt;/span&gt; inputs.Aggregate(
        (&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt;) &lt;span style="color:blue"&gt;new&lt;/span&gt; T[][] { &lt;span style="color:blue"&gt;new&lt;/span&gt; T[0] },
        (soFar, input) =&amp;gt;
            &lt;span style="color:blue"&gt;from&lt;/span&gt; prevProductItem &lt;span style="color:blue"&gt;in&lt;/span&gt; soFar
            &lt;span style="color:blue"&gt;from&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; input
            &lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(&lt;span style="color:blue"&gt;new&lt;/span&gt; T[] { item }));
}

&lt;span style="color:green"&gt;// Enable variable argument list.&lt;/span&gt;
&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; CartesianProduct&amp;lt;T&amp;gt;(
    &lt;span style="color:blue"&gt;params&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;[] inputs)
{
    &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt;&amp;gt; e = inputs;
    &lt;span style="color:blue"&gt;return&lt;/span&gt; CartesianProduct(e);
}
&lt;/pre&gt;
&lt;p&gt;I can now modify our &lt;code&gt;Numbers&lt;/code&gt; method to return a more specifically typed enumeration, and I can remove that ugly call to &lt;code&gt;Cast&lt;/code&gt; as well:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt; Numbers(&lt;span style="color:blue"&gt;int&lt;/span&gt; radix, &lt;span style="color:blue"&gt;int&lt;/span&gt; digits)
{
    &lt;span style="color:blue"&gt;var&lt;/span&gt; digitValues = &lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Range(0, radix);
    &lt;span style="color:blue"&gt;return&lt;/span&gt; CartesianProduct(&lt;span style="color:dimgray"&gt;Enumerable&lt;/span&gt;.Repeat(digitValues, digits));
}
&lt;/pre&gt;
&lt;p&gt;That &lt;code&gt;Repeat&lt;/code&gt; method reminds me of a minor omission from LINQ that has caused our &lt;code&gt;CartesianProduct&lt;/code&gt; to be slightly messier than necessary. I’ll clean things up further by adding some helpers in the next blog in this series.&lt;/p&gt;</description></item><item><title>Moving Away from Anonymous Types</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2</guid><link>http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2</link><pubDate>Thu, 29 Jul 2010 21:05:19 GMT</pubDate><description>&lt;p&gt;This is part two in a series of blogs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1"&gt;Simple but Too Specialized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Moving Away from Anonymous Types (this entry)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3"&gt;LINQ to LINQ&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4"&gt;The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5"&gt;Other Languages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6"&gt;Closing Thoughts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Part 2 – Moving Away from Anonymous Types&lt;/h3&gt;
&lt;p&gt;In the previous article, I showed how you can combine multiple LINQ &lt;code&gt;SelectMany&lt;/code&gt; calls to produce a multi-way Cartesian product. So far, I’ve used anonymous types to manage each increase in complexity—I just added a new property for each new input set. This is really handy when you know exactly what sets you’re working with, but if you want to deal with arbitrary numbers of sets, you need a slightly more general purpose representation.&lt;/p&gt;
&lt;p&gt;What exactly do we need? Well remember, the Cartesian product of two sets produces a set containing pairs of items. (E.g., (A, 1) or (B, 3).) With three sets involved, rather than pairs we get what you might call “triples” such as (A, 2, Red), and with four input sets you get a set of “quadruples” and so on. The general name for a pair, triple, quadruple, quintuple, etc. is a &lt;a href="http://en.wikipedia.org/wiki/Tuple"&gt;Tuple&lt;/a&gt;, or n-Tuple, so you might think that the &lt;a href="http://msdn.microsoft.com/library/system.tuple"&gt;Tuple class&lt;/a&gt; (introduced in .NET 4.0) would be just the thing. But in fact, that’s designed for when you know how many items you want in your tuple at compile time, just like anonymous types. (The main advantage of &lt;code&gt;Tuple&lt;/code&gt; over an anonymous type is that you can use &lt;code&gt;Tuple&lt;/code&gt; in method and property signatures; anonymous types are effectively confined to the scope in which they are constructed.) A tuple is the right concept but the &lt;code&gt;Tuple&lt;/code&gt; class is the wrong representation here.&lt;/p&gt;
&lt;p&gt;A tuple is just an ordered set of items. So I could just use an array. For example, if you produce the Cartesian product of three sets, I can represent each item in the results using something like &lt;code&gt;new &lt;/code&gt;&lt;code&gt;object[&lt;/code&gt;&lt;code&gt;]&lt;/code&gt;&lt;code&gt; { 'A', 3, "Red" }&lt;/code&gt;. I can rewrite the last two queries from the previous blog in this series to use this representation:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; lettersAndNumbersCartesianProduct = letters.SelectMany(
    letter =&amp;gt; numbers.Select(number =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[] { letter, number }));

&lt;span style="color:blue"&gt;var&lt;/span&gt; cartesianProduct = lettersAndNumbersCartesianProduct.SelectMany(
    (letterAndNumber) =&amp;gt; colours.Select(colour =&amp;gt;
        &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt; [] { letterAndNumber[0], letterAndNumber[1], colour }));

&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;var&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; cartesianProduct)
{
    &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:blue"&gt;string&lt;/span&gt;.Join(&lt;span style="color:brown"&gt;","&lt;/span&gt;, item));
}
&lt;/pre&gt;
&lt;p&gt;Now, &lt;code&gt;lettersAndNumbersCartesianProduct&lt;/code&gt; and &lt;code&gt;cartesianProduct&lt;/code&gt; are both &lt;code&gt;IEnumerable&lt;/code&gt;&lt;code&gt;&amp;lt;&lt;/code&gt;&lt;code&gt;object[&lt;/code&gt;&lt;code&gt;]&amp;gt;&lt;/code&gt;, i.e., they are sequences where each item in the sequence is an array. I’ve modified the &lt;code&gt;foreach&lt;/code&gt; loop to expect a sequence of arrays, so the output now looks like this:&lt;/p&gt;
&lt;pre&gt;A,1,Red
A,1,Blue
A,2,Red
A,2,Blue
A,3,Red
A,3,Blue
A,4,Red
A,4,Blue
B,1,Red
B,1,Blue
B,2,Red
B,2,Blue
B,3,Red
B,3,Blue
B,4,Red
B,4,Blue
C,1,Red
C,1,Blue
C,2,Red
C,2,Blue
C,3,Red
C,3,Blue
C,4,Red
C,4,Blue
&lt;/pre&gt;
&lt;p&gt;This is less convenient—the items produced by this code are just arrays, rather than statically-typed anonymous types with conveniently-named members like &lt;code&gt;number&lt;/code&gt; and &lt;code&gt;colour&lt;/code&gt;. However, I’m now in a position to generalise—I’ve got one type, &lt;code&gt;IEnumerable&lt;/code&gt;&lt;code&gt;&amp;lt;&lt;/code&gt;&lt;code&gt;object[&lt;/code&gt;&lt;code&gt;]&amp;gt;&lt;/code&gt;, capable of representing the Cartesian product any number of sets. For an n-ary product, each array in the sequence will be of length n. If I want to add in another set, the output can still be represented as an &lt;code&gt;IEnumerable&lt;/code&gt;&lt;code&gt;&amp;lt;&lt;/code&gt;&lt;code&gt;object[&lt;/code&gt;&lt;code&gt;]&amp;gt;&lt;/code&gt;, with each array being of length n+1. This lets me write a method that produces the Cartesian product of multiple sets iteratively:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;public&lt;/span&gt; &lt;span style="color:blue"&gt;static&lt;/span&gt; &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt; CartesianProduct(&lt;span style="color:blue"&gt;params&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] inputs)
{
    &lt;span style="color:dimgray"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color:blue"&gt;object&lt;/span&gt;[]&amp;gt; soFar = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[][] { &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[0] };
    &lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;var&lt;/span&gt; input &lt;span style="color:blue"&gt;in&lt;/span&gt; inputs)
    {
        &lt;span style="color:blue"&gt;var&lt;/span&gt; currentInput = input;
        soFar = soFar.SelectMany(prevProductItem =&amp;gt;
            &lt;span style="color:blue"&gt;from&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; currentInput
            &lt;span style="color:blue"&gt;select&lt;/span&gt; prevProductItem.Concat(&lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:blue"&gt;object&lt;/span&gt;[] { item }).ToArray());
    }
    &lt;span style="color:blue"&gt;return&lt;/span&gt; soFar;
}
&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;soFar&lt;/code&gt; variable is used to build up the result, one input set at a time, so its initial value represents the Cartesian product of zero sets. I’ve chosen to represent this as a sequence containing a single zero-length array. You could argue that the result for no input sets should be an empty sequence, so it may look odd to return a sequence with a single item when there are no input sets. But you can also argue that there’s exactly one possible outcome when you have no input sets—the empty set—and so the result should be a sequence containing that one outcome. (I.e., the result is a sequence containing the empty set.) That second choice happens to work better as a starting point for chaining multiple product queries together, so I’ve gone with that. And the loop just goes round chaining a &lt;code&gt;SelectMany&lt;/code&gt; query onto the previous query for each of the input sets.&lt;/p&gt;
&lt;p&gt;This does the job, but I’m doing work LINQ could be doing for me, as we’ll see next time.&lt;/p&gt;</description></item><item><title>LINQ and N-ary Cartesian Products</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1</guid><link>http://www.interact-sw.co.uk/iangblog/2010/07/28/linq-cartesian-1</link><pubDate>Wed, 28 Jul 2010 19:21:32 GMT</pubDate><description>&lt;p&gt;I recently found myself needing to solve a problem that involved producing an n-ary Cartesian product. I ended up with a fun solution in which I used LINQ to generate a LINQ query. I thought I’d share it. Being me, I spent quite a while writing a blog about this, tinkering with the details, and leaving it for a few days so I could re-read the text with a fresher point of view. And then I got distracted. And then it got so large that I split it up.&lt;/p&gt;
&lt;p&gt;The problem with sitting on a draft of a blog post for that long is that there’s a good chance that &lt;a href="http://blogs.msdn.com/b/ericlippert/"&gt;Eric Lippert&lt;/a&gt; will write &lt;a href="http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx"&gt;a post on exactly the same topic&lt;/a&gt; in between me starting to write the post and actually publishing it.&lt;/p&gt;
&lt;p&gt;Ah well. I ended up with a slightly different solution from Eric. Also, the main reason I was delaying this was that I wanted to get a couple of examples from other languages together. So I hope this will be interesting even to people who have already read Eric’s post.&lt;/p&gt;
&lt;p&gt;This ended up being rather longer than I had anticipated, so I’m breaking it up into a series.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Simple but Too Specialized (this entry)&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/07/29/linq-cartesian-2"&gt;Moving Away from Anonymous Types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/01/linq-cartesian-3"&gt;LINQ to LINQ&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/02/linq-cartesian-4"&gt;The Missing LINQ: IEnumerable&amp;lt;T&amp;gt; and Scalars&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/05/linq-cartesian-5"&gt;Other Languages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.interact-sw.co.uk/iangblog/2010/08/08/linq-cartesian-6"&gt;Closing Thoughts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Part 1 – Simple but Too Specialized&lt;/h3&gt;
&lt;p&gt;Before getting to the general n-ary case, let’s start with a simple case: the Cartesian product of two sets, or a cross join, as it’s known in databases. If you’re not familiar with this operation, it just produces every possible pairing between the items from two sets. This is easy in C# thanks to LINQ:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;char&lt;/span&gt;[] letters = { &lt;span style="color:brown"&gt;'A'&lt;/span&gt;, &lt;span style="color:brown"&gt;'B'&lt;/span&gt;, &lt;span style="color:brown"&gt;'C'&lt;/span&gt; };
&lt;span style="color:blue"&gt;int&lt;/span&gt;[] numbers = { 1, 2, 3, 4 };

&lt;span style="color:blue"&gt;var&lt;/span&gt; cartesianProduct = &lt;span style="color:blue"&gt;from&lt;/span&gt; letter &lt;span style="color:blue"&gt;in&lt;/span&gt; letters
                       &lt;span style="color:blue"&gt;from&lt;/span&gt; number &lt;span style="color:blue"&gt;in&lt;/span&gt; numbers
&lt;span style="color:blue"&gt;                       select&lt;/span&gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { letter, number };

&lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;var&lt;/span&gt; item &lt;span style="color:blue"&gt;in&lt;/span&gt; cartesianProduct)
{
    &lt;span style="color:dimgray"&gt;Console&lt;/span&gt;.WriteLine(item);
}&lt;/pre&gt;
&lt;p&gt;I start with two lists—the letters A, B, and C, and the numbers 1-4—and the output shows all the possible pairs:&lt;/p&gt;
&lt;pre&gt;{ letter = A, number = 1 }
{ letter = A, number = 2 }
{ letter = A, number = 3 }
{ letter = A, number = 4 }
{ letter = B, number = 1 }
{ letter = B, number = 2 }
{ letter = B, number = 3 }
{ letter = B, number = 4 }
{ letter = C, number = 1 }
{ letter = C, number = 2 }
{ letter = C, number = 3 }
{ letter = C, number = 4 }
&lt;/pre&gt;
&lt;p&gt;That’s fine as far as it goes, but I needed to deal with more than two lists. LINQ can handle this too—you can have as many &lt;code&gt;from&lt;/code&gt; clauses as you like:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;char&lt;/span&gt;[] letters = { &lt;span style="color:brown"&gt;'A'&lt;/span&gt;, &lt;span style="color:brown"&gt;'B'&lt;/span&gt;, &lt;span style="color:brown"&gt;'C'&lt;/span&gt; };
&lt;span style="color:blue"&gt;int&lt;/span&gt;[] numbers = { 1, 2, 3, 4 };
&lt;span style="color:blue"&gt;string&lt;/span&gt;[] colours = { &lt;span style="color:brown"&gt;"Red"&lt;/span&gt;, &lt;span style="color:brown"&gt;"Blue"&lt;/span&gt; };

&lt;span style="color:blue"&gt;var&lt;/span&gt; cartesianProduct = &lt;span style="color:blue"&gt;from&lt;/span&gt; letter &lt;span style="color:blue"&gt;in&lt;/span&gt; letters
                       &lt;span style="color:blue"&gt;from&lt;/span&gt; number &lt;span style="color:blue"&gt;in&lt;/span&gt; numbers
                       &lt;span style="color:blue"&gt;from&lt;/span&gt; colour &lt;span style="color:blue"&gt;in&lt;/span&gt; colours
                       &lt;span style="color:blue"&gt;select new&lt;/span&gt; { letter, number, colour };
&lt;/pre&gt;
&lt;p&gt;This produces the following output:&lt;/p&gt;
&lt;pre&gt;{ letter = A, number = 1, colour = Red }
{ letter = A, number = 1, colour = Blue }
{ letter = A, number = 2, colour = Red }
{ letter = A, number = 2, colour = Blue }
{ letter = A, number = 3, colour = Red }
{ letter = A, number = 3, colour = Blue }
{ letter = A, number = 4, colour = Red }
{ letter = A, number = 4, colour = Blue }
{ letter = B, number = 1, colour = Red }
{ letter = B, number = 1, colour = Blue }
{ letter = B, number = 2, colour = Red }
{ letter = B, number = 2, colour = Blue }
{ letter = B, number = 3, colour = Red }
{ letter = B, number = 3, colour = Blue }
{ letter = B, number = 4, colour = Red }
{ letter = B, number = 4, colour = Blue }
{ letter = C, number = 1, colour = Red }
{ letter = C, number = 1, colour = Blue }
{ letter = C, number = 2, colour = Red }
{ letter = C, number = 2, colour = Blue }
{ letter = C, number = 3, colour = Red }
{ letter = C, number = 3, colour = Blue }
{ letter = C, number = 4, colour = Red }
{ letter = C, number = 4, colour = Blue }
&lt;/pre&gt;
&lt;p&gt;That’s a 3-way Cartesian product. You can keep adding as many &lt;code&gt;from&lt;/code&gt; clauses as you like, because LINQ supports n-ary Cartesian products. Problem solved? Not quite. This approach is perfect if you know how many sets you’re combining at compile time—in these examples, I knew what the ‘n’ in n-ary was when writing the code. (2, and 3, respectively.)&lt;/p&gt;
&lt;p&gt;But in the problem I’m trying to solve, I didn’t have that information at compile time. I need to produce the n-ary Cartesian product across a bunch of sets where I don’t know how many sets there would be until runtime.&lt;/p&gt;
&lt;p&gt;But this doesn’t stop me from using LINQ. A LINQ query is just an object built up by a series of method calls—the query expression syntax I used in the last couple of examples disguises this, but explicit method calls offer a bit more power. LINQ queries with multiple &lt;code&gt;from&lt;/code&gt; clauses use the &lt;code&gt;SelectMany&lt;/code&gt; operator beneath the covers, so that last query is equivalent to this:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:blue"&gt;var&lt;/span&gt; lettersAndNumbersCartesianProduct = letters.SelectMany(
    letter =&amp;gt; numbers.Select(number =&amp;gt; &lt;span style="color:blue"&gt;new&lt;/span&gt; { letter, number }));

&lt;span style="color:blue"&gt;var&lt;/span&gt; cartesianProduct = lettersAndNumbersCartesianProduct.SelectMany(
    (letterAndNumber) =&amp;gt; colours.Select(colour =&amp;gt;
        &lt;span style="color:blue"&gt;new&lt;/span&gt; { letterAndNumber.letter, letterAndNumber.number, colour }));
&lt;/pre&gt;
&lt;p&gt;More generally, if you have N &lt;code&gt;from&lt;/code&gt; clauses you will have N-1 calls to &lt;code&gt;SelectMany&lt;/code&gt;. (You’ll notice that I’ve now got two anonymous types—the one used to contain the pairs produced by the first &lt;code&gt;SelectMany&lt;/code&gt; is fed into the second &lt;code&gt;SelectM&lt;/code&gt;&lt;code&gt;any&lt;/code&gt; that produces the (letter, number, colour) ‘triples’ that make up my final output. One of the advantages of using the C# query expression syntax is that the C# compiler hides all of this sort of stuff for you. If you inspect the code C# produces for the query expression version, using ILDASM or Reflector, you’ll see it’s doing something similar under the covers.)&lt;/p&gt;
&lt;p&gt;I split the last example into two statements to highlight a useful fact: if I need a 3-way Cartesian product, I can start with a 2-way Cartesian product, and then just bolt an extra &lt;code&gt;SelectMany&lt;/code&gt; on the end. This technique of taking an existing LINQ query and invoking an extra operator on it to form a more complex query is sometimes called chaining.&lt;/p&gt;
&lt;p&gt;I can take this a step further and build a general purpose method that takes any number ‘n’ of sets and produces the n-ary Cartesian product of those sets by repeatedly chaining &lt;code&gt;SelectMany&lt;/code&gt; calls. However, I’d need to come up with a slightly more adaptable representation. As it stands, with each set I add to the product, the resulting set’s members grow more complex. The Cartesian product of numbers and letters produced a set where each member had both a number and a letter, e.g. { letter = 'A', number = 2 } or { letter = 'C', number = 1 }. The Cartesian product of numbers letters, and colours produced a set where each member had three items, looking like { letter = A, number = 3, colour = "Red" } or { letter = B, number = 2, colour = "Blue" }.&lt;/p&gt;
&lt;p&gt;I’ll have to abandon anonymous types to generalize this—anonymous types are great when you know at compile time exactly what you’ll be dealing with. But they cannot adapt at runtime. So in the next blog in this series, I’ll use a different representation, so that I can write a generalized method for producing an n-ary Cartesian product.&lt;/p&gt;</description></item><item><title>Silverlight 3 at PDC</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2009/09/05/silverlight-3-pdc</guid><link>http://www.interact-sw.co.uk/iangblog/2009/09/05/silverlight-3-pdc</link><pubDate>Sat, 05 Sep 2009 15:42:01 GMT</pubDate><description>&lt;p&gt;I’m absurdly excited about &lt;a href="http://microsoftpdc.com/"&gt;PDC&lt;/a&gt; this year because for the first time, I’ll be speaking there! &lt;a href="http://twitter.com/RichGee"&gt;Rich Griffin&lt;/a&gt; and I will be &lt;a href="http://microsoftpdc.com/Sessions/Getting-the-most-out-of-Silverlight-3"&gt;talking about Silverlight 3&lt;/a&gt;. This is one of the day-long &lt;a href="http://microsoftpdc.com/Workshops"&gt;workshops&lt;/a&gt; that run the day before the full conference starts.&lt;/p&gt;
&lt;p&gt;I’m pleased to be talking with someone who I’ve worked with as a fellow developer—Rich and I have collaborated on some of the many WPF and Silverlight projects we’ve worked on over the last few years. We both have a lot of experience solving real problems, and we’re looking forward to bringing that to the workshop—we will be talking about building real software.&lt;/p&gt;
&lt;p&gt;PDC is just over a couple of months away, so we haven’t quite set our talks in stone yet. We’d both love to &lt;a href="mailto:ian@interact-sw.co.uk;gripp@hotmail.com?subject=SL3%20PDC%20Workshop%20Suggestions"&gt;hear from you&lt;/a&gt; if you’re contemplating coming to our session and have ideas on what you’d like to see. That said, we obviously need to give people a fair idea of what to expect so they can plan now. So here’s what we’re currently thinking.&lt;/p&gt;
&lt;p&gt;We see the day breaking down into four pieces, taking roughly a quarter of the day each: The Ideas of Silverlight; Connecting; Software Design; Working with Designers. &lt;/p&gt;
&lt;h3&gt;The Ideas of Silverlight&lt;/h3&gt;
&lt;p&gt;I want to start by saying what this will &lt;i&gt;NOT&lt;/i&gt; be. We absolutely don’t want to do a laundry list of Silverlight features, or a straight forward walk through of the developer and the design tools. We believe that a sound understanding of a critical set of ideas at the heart of Silverlight is the secret to true proficiency.&lt;/p&gt;
&lt;p&gt;So we plan to talk about some features that make Silverlight very different from most other UI technologies, and how they combine in ways you might not expect. In particular, we plan to describe the roles played by templates, and styles, the structure of controls, the surprising importance of data binding, and why something called MVVM is so important. We also want to talk about some of the practical issues around deployment, testing, and tools.&lt;/p&gt;
&lt;h3&gt;Connecting&lt;/h3&gt;
&lt;p&gt;Silverlight is for the internet, so our second section will be all about how to connect with the rest of the world. We plan to look at WCF, REST, and POX in some depth. We’ll discuss the tension between security and flexibility, and some practical resolutions. We’ll talk about RIA services too, although since that’s a topic that could easily fill a day on its own, we don’t intend to cover it in depth—our current thinking is that we want to make it clear what it’s for and when you would or wouldn’t use it, illustrating just enough of it that you’ll see its overall approach. (Although if you think we should dedicate a large chunk of the day to RIA services, we’d like to hear from you, and we’d like to know what you think we should drop to make space for it.)&lt;/p&gt;
&lt;h3&gt;Software Design&lt;/h3&gt;
&lt;p&gt;It’s all very well to look at the core ideas, features and technologies of Silverlight, both on the inside, and where your code meets the rest of the world, but how do you tie it all together in practice? We’ll look at strategies for structuring your application’s design. (That’s software design, as opposed to interaction design or visual design, by the way.) We expect to go into more detail on MVVM here. We’d also like to talk about where technologies such as MEF and Prism can fit in.&lt;/p&gt;
&lt;h3&gt;Working with Designers&lt;/h3&gt;
&lt;p&gt;Yes, PDC is for developers. So is this session. Building Silverlight applications that look great takes more than throwing a finished application over the wall to where the visual designers work and asking them to slap a layer of sparkle on at the last minute. Integrating good visual design into your application requires planning. Developers need to understand the process and get involved. The way to get the best results is for developers and designers to work together closely. We’ll talk about the steps you need to take as developers to make this possible. We’ll also show how Blend fits into the world of the developer, and we’ll offer tips for how it can make your life easier when creating Silverlight applications.&lt;/p&gt;
&lt;p&gt;So that’s the current plan. I’ll be posting more as we refine our ideas, and most likely &lt;a href="http://twitter.com/idg10"&gt;tweeting&lt;/a&gt; &lt;a href="http://twitter.com/RichGee"&gt;too&lt;/a&gt;—we might do a couple of polls to gauge the level of interest in the various topics, so now is the perfect time for feedback. We look forward to your suggestions!&lt;/p&gt;
&lt;p&gt;(If you’re wondering about why I only just mentioned this, when it was all announced a few weeks ago, I came on board to speak just as I went off on an extended holiday, and now that I’m back, I’m feverishly trying to catch up with everything.)&lt;/p&gt;</description></item><item><title>Designing a WPF Timeline Control Part 1: Structure</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2009/06/04/wpf-timeline-control-design</guid><link>http://www.interact-sw.co.uk/iangblog/2009/06/04/wpf-timeline-control-design</link><pubDate>Thu, 04 Jun 2009 02:38:22 GMT</pubDate><description>&lt;p&gt;For a change, I’m involved in an endeavour I can blog about. I’m working with &lt;a href="http://mcwtech.com/CS/blogs/brianr/default.aspx"&gt;Brian Randell&lt;/a&gt;, &lt;a href="http://blogs.ythos.net/"&gt;Matthew Adams&lt;/a&gt;, and &lt;a href="http://blogs.conchango.com/felixcorke/"&gt;Felix Corke&lt;/a&gt; on a &lt;a href="http://mcwtech.com/CS/blogs/brianr/archive/2009/03/29/dinner-and-a-new-project.aspx"&gt;project&lt;/a&gt; that involves building a kind of timeline control. This blog describes the thinking behind the control’s structure—WPF controls tend to end up looking very different from their equivalents in anything based on classic Win32 UI underpinnings such as Windows Forms, and I thought it might be interesting to explain how and why the differences come about.&lt;/p&gt;
&lt;p&gt;We’re not quite ready to show the code for this yet, as it’s still a work in progress, but we’ll make the source available before too long.&lt;/p&gt;
&lt;h3&gt;Requirements&lt;/h3&gt;
&lt;p&gt;The requirements were a little nebulous, because we set out to build a control for fun, rather than for any particular application or customers. So one of the most important requirements was that it be interesting to build. Nonetheless, we had some ideas about what sorts of things we wanted to be able to do. For example we wanted a way to show files found via &lt;a href="http://www.microsoft.com/windows/products/winfamily/desktopsearch/default.mspx"&gt;Windows Search&lt;/a&gt; (or, as I find it hard to stop calling it, Windows Desktop Search). Positioning and grouping files by dates along a timeline seemed like it might be an interesting way to visualize search results.&lt;/p&gt;
&lt;p&gt;Here’s an early prototype we built to get a rough idea of how it might work with some real data. I’m jumping ahead here a little, but a picture makes it easier to understand what we had in mind:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.interact-sw.co.uk/images/Crummy-Timeline.png" alt="Screenshot of prototype timeline user interface - this is what happens when you let developers design UX"&gt;&lt;/p&gt;
&lt;p&gt;The user can drag the whole timeline left or right to move around, and zoom in and out with the mouse. The items are all expanded in that example above. It doesn’t have to be that way though—here’s how it might look when the user has zoomed out a bit and only has one item expanded:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.interact-sw.co.uk/images/Crummy-Timeline-Distribution.png" alt="Prototype timeline showing mostly collapsed groups, with a sort of bar graph representation of how much stuff is in these groups"&gt;&lt;/p&gt;
&lt;p&gt;Clearly we have a bit of a problem with the captions on the timeline here, but you can see how this gives an impression of which bits of the timeline have a lot of content, and which bits are empty. Notice that in this example we also experimented with vertically stacked bars to indicate how much stuff was inside each group, to give a better idea of information density over time.&lt;/p&gt;
&lt;p&gt;Now obviously this example looks horrible. Our goal at this stage was to try out some ideas to see if they would work before building something properly. As you’ll see in future blogs, it started looking a lot better once Felix got his hands on it.&lt;/p&gt;
&lt;p&gt;Another feature we wanted was the ability to support multiple levels of detail—we envisaged the initial view as being a bunch of blobs on the timeline indicating files placed by date, which could be expanded to reveal details, possibly multiple levels of detail. So the examples above aggregate a bunch of files that appear in quick succession as a single blob, showing a list of all the files if you click on that blob, but we might want to go further, with some sort of details fly-out available on each of the items in that list.&lt;/p&gt;
&lt;p&gt;We also wanted to avoid assuming much about the nature of the data source. We had discussed various ideas for what we might want to display along a timeline—I forget the complete list, but TV schedule information, appointment booking, gaming, and project management came up as possible application areas.&lt;/p&gt;
&lt;p&gt;So our ‘spec’ was pretty vague (although I’ve had worse). We decided to start with the file system/search example, and see where it took us—more a voyage of exploration than a software project. Perhaps not the most efficient approach to software development, but if you’re building a UI component of a kind you’ve not attempted before, it’s not a bad idea to be at least a little chaotic—your first design is unlikely to be your best, so some space to experiment is useful.&lt;/p&gt;
&lt;p&gt;But where to start? If you want a custom control to get the best out of WPF, it’s a good idea to try and align yourself with WPF’s philosophy. But what is that, exactly?&lt;/p&gt;
&lt;h3&gt;Composition is King&lt;/h3&gt;
&lt;p&gt;I’ve long thought that WPF’s single biggest benefit is its composition-based approach. Examine most of the built-in controls, and you’ll find that they do less work than you might think, deferring to other WPF components to get the job done. And these subordinate components are almost invariably multi-purpose—they show up in other WPF controls, and can be used where appropriate in your own custom controls.&lt;/p&gt;
&lt;p&gt;Take the &lt;code&gt;ListBox&lt;/code&gt;. Amongst the things it doesn’t know how to do are: size and position the list items; render list items; provide selection highlighting; provide its own appearance. For these tasks it defers to its items panel, its item template, its item containers, and its control template respectively, and you can plug in your own objects for any of these, to customize the control. Of these, only the item container type (&lt;code&gt;ListBoxItem&lt;/code&gt;) is specific to the &lt;code&gt;ListBox&lt;/code&gt;, and even that shares a lot in common with other list controls’ items containers.&lt;/p&gt;
&lt;p&gt;A single monolithic black box of a control might be in keeping with long-standing traditions of the Windows 3rd party control market, but it’s not the WPF way.&lt;/p&gt;
&lt;h3&gt;Areas of Responsibility&lt;/h3&gt;
&lt;p&gt;The WPF way is for each area of responsibility to be owned by a separate type. This is not a new idea, of course, but it’s one that seems to be less well represented in the UI layer than elsewhere.&lt;/p&gt;
&lt;p&gt;When developing new UI element types, we design them to be combined in the ways we need them to work, and with luck, it will be possible to combine them usefully in ways we did not first anticipate. In fact that second part often requires more than luck—types are rarely reusable in practice until you’ve tried to use them in multiple scenarios and have fixed the problems that made them less useful than you had hoped. We haven’t done that yet for these controls, so this is probably not yet the definitive design.&lt;/p&gt;
&lt;p&gt;So, what are the areas of responsibility we think exist for our timeline UI? Here’s a breakdown, along with a suggestion of what kind of object might fit the bill:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Generation of UI elements from a data source (&lt;code&gt;ItemsControl&lt;/code&gt;?)&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Visual representation of the ‘line’ in the timeline control (&lt;code&gt;ControlTemplate&lt;/code&gt;?)&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Control to provide panning/scrolling (&lt;code&gt;ScrollViewer&lt;/code&gt;?)&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Positioning of UI elements along a line (&lt;code&gt;Panel&lt;/code&gt;?)&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Generated element type to be positioned on the line (some sort of &lt;code&gt;ContentControl&lt;/code&gt; or &lt;code&gt;Expander&lt;/code&gt;?)&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Visual representation of an item on the line (&lt;code&gt;ControlTemplate&lt;/code&gt;?)&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Expanded view of content of generated element (&lt;code&gt;DataTemplate&lt;/code&gt;?)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You’ll notice that we have borrowed shamelessly from the pattern established by WPF’s various items controls. We can produce a very similar-looking list for &lt;code&gt;ListBox&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Derives from &lt;code&gt;ItemsControl&lt;/code&gt;, enabling it to generate items from a data source&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Being a control it has a &lt;code&gt;ControlTemplate&lt;/code&gt; to define its appearance&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Relies on &lt;code&gt;ScrollViewer&lt;/code&gt; to provide a scrollable area&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Uses a &lt;code&gt;VirtualizingStackPanel&lt;/code&gt; to position its elements vertically&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;Generates a &lt;code&gt;ListBoxItem&lt;/code&gt; (which is a &lt;code&gt;ContentControl&lt;/code&gt;) for each item in the list&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;&lt;code&gt;ListBoxItem&lt;/code&gt; is a control, so it also has a template&lt;/li&gt;
&lt;li&gt;
    &lt;p&gt;&lt;/p&gt;&lt;code&gt;ItemTemplate&lt;/code&gt; or implicit data template used to render items in the list&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If WPF already has a pattern that meets your needs, it’s usually a good idea to follow suit. Anyone already familiar with WPF will find your code easier to follow, and it also means you’re on a path likely to lead somewhere useful. But the degree of similarity here raises an obvious question: could we get away without creating any custom elements at all?&lt;/p&gt;
&lt;h3&gt;No Custom Elements?&lt;/h3&gt;
&lt;p&gt;It’s surprisingly common for WPF applications to be able to cobble together various WPF elements to achieve effects that would have required a custom control in Windows Forms. Could we do that here?&lt;/p&gt;
&lt;p&gt;As an early experiment we built an application that queried Windows Search for all the bitmaps on a system, used LINQ to group them by month, and dumped the results into an &lt;code&gt;ItemsControl&lt;/code&gt; to produce a timeline. To keep it simple we just used a &lt;code&gt;StackPanel&lt;/code&gt; to get the items in order, but not yet positioned precisely according to date. The &lt;code&gt;ItemTemplate&lt;/code&gt; contained a list of the files, using an &lt;code&gt;Image&lt;/code&gt; element to render the actual image file. This list was initially collapsed, but could be expanded by clicking a button.&lt;/p&gt;
&lt;p&gt;It rapidly became obvious that this wasn’t going to fly from a performance perspective. Even with the image lists initially collapsed, mere invisibility wasn’t enough to prevent the &lt;code&gt;Image&lt;/code&gt; elements from being created. This meant that when the application started, it would attempt to load every single bitmap found by Windows Search. We let it run for a while to enjoy the spectacle of a single process consuming over 4GB of memory—it’s entertaining to pretend you have a justification for owning a 64-bit system—before giving up and killing it off.&lt;/p&gt;
&lt;p&gt;The naive approach clearly wasn’t going to work, but we could make a small change to reduce the memory footprint: we decided to take the image loading out of WPF’s &lt;code&gt;Image&lt;/code&gt; element’s hands. Instead of binding the &lt;code&gt;Image&lt;/code&gt; element’s &lt;code&gt;Source&lt;/code&gt; directly to the bitmap path, we wrote some code to load the image. This gave us the option to specify a size for the loaded image—since we were only showing thumbnails, we told WPF to decode the image to a much smaller size, just 40x30 pixels. This way it was at least conceivable that all the images we were trying to load might fit in memory. This ‘improved’ matters in the sense that the application progressed from not working at all to working unusably slowly.&lt;/p&gt;
&lt;p&gt;It was starting to look like some form of virtualization might be necessary.&lt;/p&gt;
&lt;p&gt;(This is of course all utterly predictable. Less subtle minds than your own might even conclude that we were idiots for bothering to try this naive approach. But I’ve learned that it’s wise to start your performance investigations with the parts you can predict. That way you get to find out which of your predictions were wrong. Plus, you might get to observe things going wrong in a slightly different fashion from the one you expected, which can offer useful insights. Indeed, besides the rather obvious expected memory consumption problems, we observed some CPU-bound performance issues in the image handling in some places that surprised us, and which uncovered an opportunity to significantly speed up our eventual load time performance which might have been harder to spot at a later stage. I’ll cover this in a later blog.)&lt;/p&gt;
&lt;p&gt;A couple of options stood out for improving the bitmap handling. We could get slightly cleverer with the expansion of the per-group list: rather than merely collapsing the list until the user expanded it, we could arrange not to create the list at all until needed—that should avoid the premature (and rather expensive) loading of every bitmap on the system. Or we could use a virtualizing panel for the main timeline items control, so that the groups’ UIs didn’t get instantiated at all until they appeared on screen. We tried both.&lt;/p&gt;
&lt;p&gt;Either of these on their own produced a profound improvement—the application went from “Fail slowly” to “Sub-second load” performance. However, using just one or the other wasn’t enough to get that “sub-second” quite “sub-” enough—we were seeing a half second UI freeze between the Windows Search results coming back and the results being displayed. Only with both techniques applied was the performance satisfactory.&lt;/p&gt;
&lt;p&gt;So we need at least one custom element: our panel needs to virtualize, and the only built-in virtualizing panel is the &lt;code&gt;VirtualizingStackPanel&lt;/code&gt;. That doesn’t give us the positioning we want: we need to be able to select a position based on some date. Only &lt;code&gt;Canvas&lt;/code&gt; and &lt;code&gt;Grid&lt;/code&gt; make that sort of control possible, and neither of those can virtualize. So we need our own panel. We provisionally chose to call this a &lt;code&gt;VirtualizingOffsetPanel&lt;/code&gt;, for want of a better name.&lt;/p&gt;
&lt;p&gt;We also decided to build a custom control to perform the expansion. It is technically possible to get the deferred list realization needed with an &lt;code&gt;Expander&lt;/code&gt;: the trick is to use a &lt;code&gt;ContentTemplate&lt;/code&gt; rather than just making our image list the child of the &lt;code&gt;Expander&lt;/code&gt;. However, we’d be relying on a side effect of an undocumented &lt;code&gt;Expander&lt;/code&gt; behaviour. I’ve gone down a similar path before with tree view item expansion, and didn’t enjoy it. So we decided to make our own expander (which is a pretty simple thing to construct) in order to give us control over what actions occur and in which order when an item is expanded. And since this control was going to be instantiated for each item on the timeline, we decided to designate this as the item container for our timeline control. And since a custom item container requires a custom items control, we have a reason for a third custom element, the &lt;code&gt;TimelineControl&lt;/code&gt; itself.&lt;/p&gt;
&lt;p&gt;So it’s now looking like we’re going to write three custom elements: a &lt;code&gt;TimelineControl&lt;/code&gt;, a &lt;code&gt;TimelineGroupItem&lt;/code&gt;, and a &lt;code&gt;VirtualizingOffsetPanel&lt;/code&gt;. Yes, for that second one, the name &lt;code&gt;TimelineControlItem&lt;/code&gt; might have looked more consistent, but &lt;code&gt;TimelineGroupItem&lt;/code&gt; felt like a more accurate description of what it represented. So far, it still feels that way, so we’re still calling it that.&lt;/p&gt;
&lt;h3&gt;Aside: To Group or Not to Group&lt;/h3&gt;
&lt;p&gt;If you’re familiar with the capabilities of WPF data binding, you might be thinking: hold on, why aren’t you using &lt;code&gt;CollectionView.GroupDescriptions&lt;/code&gt; and a &lt;code&gt;GroupStyle&lt;/code&gt;? Well we tried that, but it seems that grouping in &lt;code&gt;ItemsControls&lt;/code&gt; has the side-effect of disabling virtualization. And since we need virtualization to get acceptable load performance, that’s a non-starter.&lt;/p&gt;
&lt;p&gt;In any case, this didn’t seem like a great loss. After a fiddling around with Windows Search for a while, LINQ started to look like an easier and more flexible way to manage grouping.&lt;/p&gt;
&lt;h3&gt;Prototyping Matters&lt;/h3&gt;
&lt;p&gt;Trying to build a working example with no custom elements at all was an important exercise. We had outlined a rough design of what we thought we probably wanted before we started. This up-front design was by no means ‘big’, but we got something wrong nonetheless. We originally thought we’d want not just the timeline and group item controls, but also an individual timeline item control. But in working through the prototype, no clear need for such a control emerged—it seems that having established a need for the &lt;code&gt;TimelineControl&lt;/code&gt;, &lt;code&gt;TimelineGroupItem&lt;/code&gt;, and &lt;code&gt;VirtualizingOffsetPanel&lt;/code&gt; items, a combination of content controls and data templates was enough to finish off the job.&lt;/p&gt;
&lt;p&gt;In future blog entries I’ll talk about how we went about building each of these custom elements.&lt;/p&gt;</description></item><item><title>Oslo WPF and Silverlight Demos</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2009/04/30/oslo-wpf-silverlight</guid><link>http://www.interact-sw.co.uk/iangblog/2009/04/30/oslo-wpf-silverlight</link><pubDate>Thu, 30 Apr 2009 15:49:57 GMT</pubDate><description>&lt;p&gt;This week I've been in Oslo, teaching a combined &lt;a href="http://www.pluralsight.com/main/ilt/course.aspx?id=AP19"&gt;Silverlight&lt;/a&gt; and &lt;a href="http://www.pluralsight.com/main/ilt/course.aspx?id=AP15"&gt;WPF&lt;/a&gt; course. For those of you who attended, here are the  &lt;a href="http://www.interact-sw.co.uk/downloads/WpfSilverlightDemos2009-04.zip"&gt;demos for download&lt;/a&gt;. And for those of you who didn't attend, well, you can download the demos too if you like.
&lt;/p&gt;</description></item><item><title>Silverlight and WriteableBitmap</title><guid isPermaLink="true">http://www.interact-sw.co.uk/iangblog/2008/11/07/silverlight-writeable-bitmap</guid><link>http://www.interact-sw.co.uk/iangblog/2008/11/07/silverlight-writeable-bitmap</link><pubDate>Fri, 07 Nov 2008 12:19:55 GMT</pubDate><description>&lt;p&gt;I’ve just released a library to CodePlex that implements a feature missing from &lt;a href="http://www.pluralsight.com/main/ilt/course.aspx?id=AP19"&gt;Silverlight&lt;/a&gt;: the ability to generate bitmaps from pixels in code at runtime. WPF provides this through its &lt;code&gt;WritableBitmap&lt;/code&gt; class, but Silverlight 2 doesn’t have that. My &lt;a href="http://www.codeplex.com/SlDynamicBitmap"&gt;SlDynamicBitmap&lt;/a&gt; project offers a solution.&lt;/p&gt;
&lt;p&gt;I was inspired to create this by the recent reports of the &lt;a href="http://adamkinney.com/blog/374/default.aspx"&gt;Silverlight port of Quake&lt;/a&gt;. From what the author says, it’s clear that they must have devised some sort of mechanism for pushing raw pixels onto the screen, something Silverlight really doesn’t help you with. I’ve been toying for a while with an idea about how you might solve this, but hadn’t tried it before. Quakelight shows that it’s definitely possible, which encouraged me to try out my idea.&lt;/p&gt;
&lt;p&gt;Incidentally, I have no idea how Quakelight solves this problem. It may well have a much more elegant solution than the ghastly hack I’m perpetrating here.&lt;/p&gt;
&lt;h3&gt;Why Would I Want This?&lt;/h3&gt;
&lt;p&gt;Before I show how it works, it’s worth reviewing why you would even want a Silverlight equivalent of WPF’s WriteableBitmap – what’s it for? It’s useful for when you want to generate pixels at runtime based on some kind of algorithm. Ray tracing is one classic example – the computer constructs an image one pixel at a time, and in order to display the results, you need some way of controlling every single pixel on a region of the screen, rather than using higher level primitives.&lt;/p&gt;
&lt;p&gt;To illustrate this I’ve chosen another classic example: a &lt;a href="http://www.interact-sw.co.uk/slapps/mandelbrot/"&gt;Mandelbrot set fractal renderer&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://www.interact-sw.co.uk/images/Silverlight-Mandelbrot.png" alt="Silverlight-Mandelbrot.png"&gt;&lt;/p&gt;
&lt;p&gt;In case you’re not familiar with &lt;a href="http://en.wikipedia.org/wiki/Mandelbrot_set"&gt;the Mandelbrot set&lt;/a&gt;, it’s a fractal generated with a deceptively simple process. It’s a striking demonstration of how incredibly basic non-linear systems can exhibit behaviour that is very complex, and which shows some very surprising geometric scaling features.&lt;/p&gt;
&lt;p&gt;But for my present purpose, the interesting thing about the Mandelbrot set is that you end up with a program that generates a lot of pixels and needs some way to get them on the screen. In WPF, this is the kind of scenario that &lt;code&gt;WriteableBitmap&lt;/code&gt; is for. To enable this in Silverlight, I’ve written a new class called &lt;code&gt;PngGenerator&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;It’s Called What?&lt;/h3&gt;
&lt;p&gt;I’ve chosen to call the main type in this library &lt;code&gt;PngGenerator&lt;/code&gt;, and not &lt;code&gt;WriteableBitmap&lt;/code&gt;. This may seem like an odd choice, but there are two good reasons for it. First, I regard this code as a workaround for a missing feature, not a proper solution, so I’m hoping that Silverlight will eventually get a &lt;code&gt;WriteableBitmap&lt;/code&gt; of its own. So it would have been unhelpful of me to use the same name. Second, the usage model has ended up being pretty different – it’s not really possible to write a custom class in Silverlight that’s a drop-in replacement for WPF’s &lt;code&gt;WriteableBitmap&lt;/code&gt;. Only Microsoft can provide us with that – it would require support from the Silverlight plug-in itself to build an exact replica.&lt;/p&gt;
&lt;p&gt;So that’s why it’s not called &lt;code&gt;WriteableBitmap&lt;/code&gt;. Why &lt;code&gt;PngGenerator&lt;/code&gt;? That’s because of the ghastly hack I used to make this work.&lt;/p&gt;
&lt;h3&gt;The Ghastly Hack&lt;/h3&gt;
&lt;p&gt;The &lt;code&gt;PngGenerator&lt;/code&gt; works by converting an array of pixel colour values into a &lt;code&gt;Stream&lt;/code&gt; of bytes that represent the image as a PNG file. (I chose PNG rather than JPEG because JPEG files typically use lossy compression, so you don’t get precisely the pixels you asked for. It has since been pointed out to me that JPEG does now support lossless images too, so I guess you could use either format. BMP would have been a whole lot easier as it’s a simpler format than either, but Silverlight only supports PNG and JPEG.)&lt;/p&gt;
&lt;p&gt;If Silverlight had an equivalent of WPF’s &lt;code&gt;PngBitmapEncoder&lt;/code&gt; class, this would have been pretty straightforward to write. Unfortunately Silverlight doesn’t contain any code to generate PNGs from pixels. So most of the code in this library is a PNG builder.&lt;/p&gt;
&lt;p&gt;By the way, I would &lt;b&gt;not&lt;/b&gt; recommend using this code to generate PNG files for general use. It does a couple of rather crufty things. It only generates the bare minimum contents required to be just enough of a legal PNG file for Silverlight to render it. And it also doesn’t compress the data. The ‘deflate’ compression format mandated by PNG lets you put in so-called ‘non-compressible’ blocks. You’re supposed to use this for any data that gets bigger when you ‘deflate’ it. Some data is just hard to compress, and the idea is that you mitigate this problem by storing that data verbatim. But I’m storing &lt;i&gt;all&lt;/i&gt; the pixel data this way to provide the simplest possible path from pixel to screen.&lt;/p&gt;
&lt;p&gt;So it’s a little too specialized to be a useful general-purpose PNG generator.&lt;/p&gt;
&lt;p&gt;I’ve seen nastier ways of solving this by the way. I’ve seen people generate Silverlight content made up of hundreds of tiny rectangles in an attempt to render their own pixel data! This doesn’t work all that brilliantly – you get anti-aliasing artefacts, and it’s mind-bogglingly slow. Unpleasant though the technique I’m using is, it does at least produce good quality results, and is tolerably quick, although not as good as a native &lt;code&gt;WriteableBitmap&lt;/code&gt; built into Silverlight could be.&lt;/p&gt;
&lt;h3&gt;Using the PngGenerator&lt;/h3&gt;
&lt;p&gt;To use the &lt;code&gt;PngGenerator&lt;/code&gt;, you do this sort of thing:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color:dimgray"&gt;PngGenerator&lt;/span&gt; pngGen = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;PngGenerator&lt;/span&gt;(640, 480);
&lt;span style="color:dimgray"&gt;Color&lt;/span&gt;[] m_pixelData = GenerateMyPixels();
pngGen.SetPixelColorData(m_pixelData);
&lt;span style="color:dimgray"&gt;BitmapImage&lt;/span&gt; imgSource = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:dimgray"&gt;BitmapImage&lt;/span&gt;();
imgSource.SetSource(pngGen.CreateStream());
myImageElement.Source = imgSource;
&lt;/pre&gt;
&lt;p&gt;That may seem slightly less direct than necessary. I’m contemplating adding a &lt;code&gt;CreateSource&lt;/code&gt;&lt;code&gt;(&lt;/code&gt;&lt;code&gt;)&lt;/code&gt; method that builds the &lt;code&gt;BitmapImage&lt;/code&gt; for you, to make the code a couple of lines shorter. But the verbose approach required by the current version does have the benefit of showing the process relatively clearly.&lt;/p&gt;
&lt;p&gt;Walking through it, we build a new &lt;code&gt;PngGenerator&lt;/code&gt;, telling it the image dimensions we require – 640x480 in this case. Then we build an array of &lt;code&gt;Color&lt;/code&gt; values indicating the pixel colours we want. (So &lt;code&gt;GenerateMyPixels&lt;/code&gt;&lt;code&gt;(&lt;/code&gt;&lt;code&gt;)&lt;/code&gt; here stands for whatever code you’ve got that generates pixel values.) We pass these pixels to the &lt;code&gt;PngGenerator&lt;/code&gt;’s &lt;code&gt;SetPixelColorData&lt;/code&gt; method. Then we construct an instance of Silverlight’s &lt;code&gt;BitmapImage&lt;/code&gt; type, and call its &lt;code&gt;SetSource&lt;/code&gt; method. (BTW, &lt;code&gt;BitmapImage.SetSource&lt;/code&gt; is the Silverlight feature that makes this possible. It accepts any &lt;code&gt;S&lt;/code&gt;&lt;code&gt;ystem.IO.S&lt;/code&gt;&lt;code&gt;tream&lt;/code&gt; object, and expects it to contain either a PNG or a JPEG.) The &lt;code&gt;PngGenerator&lt;/code&gt;’s &lt;code&gt;CreateStream&lt;/code&gt; method returns a &lt;code&gt;Stream&lt;/code&gt; that contains a PNG representing the pixels passed in to &lt;code&gt;SetPixelColorData&lt;/code&gt;. Finally, we use the &lt;code&gt;BitmapImage&lt;/code&gt; as the &lt;code&gt;Source&lt;/code&gt; property of a Silverlight &lt;code&gt;Image&lt;/code&gt; element, and the image appears.&lt;/p&gt;
&lt;p&gt;If you want to change the image, you just call &lt;code&gt;SetPixelColorData&lt;/code&gt; again, and then repeat the steps to build a &lt;code&gt;Stream&lt;/code&gt; and a &lt;code&gt;BitmapImage&lt;/code&gt;. Silverlight’s &lt;code&gt;BitmapImage&lt;/code&gt; only loads the PNG once – it doesn’t expect it to change – so we need to build a new one each time round. However, you’re free to pass the same array into &lt;code&gt;SetPixelColorData&lt;/code&gt; every time around, and internally, the &lt;code&gt;PngGenerator&lt;/code&gt; reuses all the same buffers for building the stream, so the costs of building a new frame aren’t as bad as they might be.&lt;/p&gt;
&lt;p&gt;(My first prototype did build everything from scratch each time round. It was about three times slower than the current implementation! Memory allocation and copying start to look expensive when you’re trying to push millions of pixels around several times a second.)&lt;/p&gt;
&lt;h3&gt;Silverlight and Multicore&lt;/h3&gt;
&lt;p&gt;Incidentally, the &lt;a href="http://www.interact-sw.co.uk/slapps/mandelbrot/"&gt;example&lt;/a&gt; also happens to be a clear demonstration of Silverlight’s ability to exploit multiple CPU cores on the client side. In fact the time I first ran into the absence of &lt;code&gt;WriteableBitmap&lt;/code&gt; in Silverlight was when I sat down to write exactly this Mandelbrot example as an illustration of how to use Silverlight’s multi-threading capabilities. At the time I had to abandon the idea due to the lack of writeable bitmap support. But finally, 6 months down the line, I can use the demo!&lt;/p&gt;
&lt;p&gt;The code that performs the calculations to generate the fractal image uses the thread pool to parallelize the work. Crude, but effective. On my quad core desktop, it’s really quick, despite the lack of any clever optimizations that some fractal generators use. And since I first started writing Mandelbrot rendering code on 8-bit micros with 2MHz processors back in the mid 1980s, which used to take about 3 hours to produce a puny 256x256 image, I can hardly believe how fast this runs on new hardware.&lt;/p&gt;
&lt;h3&gt;Missing Features&lt;/h3&gt;
&lt;p&gt;The code up on CodePlex is designated version 0.1 because it’s incomplete. It doesn’t support an alpha channel, i.e. no semi-transparent bitmaps. There’s no fundamental reason for this, it’s just that I’ve only had time to spend a couple of evenings on this so far. I plan to add this. I also want to add a mechanism for using raw byte arrays for pixel data instead of having to use &lt;code&gt;Color&lt;/code&gt; – there are some performance issues that this will solve. And there are a couple of places where the code is not as efficient as it could be. Right now on my machine, if I generate 1024x768 bitmaps as fast as possible it only manages about 15-20 frames per second, and I believe I can improve on that. (Although the tests I’ve performed suggests this is never going to do better than 30fps for 1024x768 on current hardware unless Silverlight evolves to provide native support for this feature.)&lt;/p&gt;
&lt;h3&gt;Getting Started&lt;/h3&gt;
&lt;p&gt;The code is up on the &lt;a href="http://www.codeplex.com/SlDynamicBitmap"&gt;SlDynamicBitmap&lt;/a&gt; project on CodePlex. You can &lt;a href="http://www.codeplex.com/SlDynamicBitmap/Release/ProjectReleases.aspx?ReleaseId=19105"&gt;download a ZIP containing both binary and source&lt;/a&gt;, or you can &lt;a href="http://www.codeplex.com/SlDynamicBitmap/SourceControl/ListDownloadableCommits.aspx"&gt;browse the source online&lt;/a&gt;. Enjoy!&lt;/p&gt;
&lt;p&gt;[&lt;b&gt;Update, 2008-11-07:&lt;/b&gt; &lt;a href="http://www.irritatedvowel.com/"&gt;Pete Brown&lt;/a&gt; pointed out to me that this has already been done... Joe Stegman has &lt;a href="http://blogs.msdn.com/jstegman/archive/2008/10/30/updated-source-for-image-samples.aspx"&gt;some code&lt;/a&gt; that enables
similar stuff. However, as far as I can tell my library is faster. Modifying Joe's code to do a 1024x768 image, it doesn't seem to be able to do more than about 5 frames per second. That's the same speed I got with my code before I started reducing the amount of copying and memory allocation. So while my contribution isn't original, its a few times faster than the existing work. So I hope it's still useful.]
&lt;/p&gt;</description></item></channel></rss>