I finally had my first “Aha!” moment with F# today. After reading Robert Pickering’s amazing article about Erlang style message passing in F# I tried to create a very dumbed-down version of a function he created. I wanted to create a function which counts how many instances there are of each type of element in a Window’s visual tree.
I’m using the WPF visual tree as a data structure to program against. Since I can easily configure a visual tree via XAML, it makes for an excellent way to create a tree structure of diverse data types. VisualTreeHelper is used to traverse that tree of elements, by calling its GetChildrenCount and GetChild methods. This brings me to my “Aha!” moment…
In my previous post I recursively walked the visual tree by using a for loop, just like I would in C#. But today that felt wrong. I forced myself to drop my old habit of manually looping, and try to think about things differently. As it turns out, F# makes it really easy to recursively walk down trees by using something called a “list comprehension.” I used that feature to “declare” that I want a list of every child element of a given element, then I forward that list to the List.iter function. The callback passed to List.iter contains the recursive call! Check out the code in the countTypes function, where the comment reads “// Process this element’s children.”
The output of running the demo application contains the output of two functions. The countTypes function output is listed second, as seen below:
I’m starting to really enjoy programming in F#.
Download the demo app here: Analyzing the visual tree in F# (demo project) Be sure to change the file extension from .DOC to .ZIP and then decompress the file. Download the F# compiler and tools here.