Flattening List in F# and C#
I was teaching someone F# and comparing it with C#. I had to bring in similarities between F# and C# and one of the key things List module. I was showing List Concatenation using “@” and also showing it C#. Here is an example of using it solving with selectmany
var x = new [] {new [] {10,20,30},new [] {40,50,60}};
x.SelectMany (y => y).ToList().ForEach(Console.WriteLine);
F# Solution
[10;20;30] @ [40;50;60]
Someone threw in a challenge by asking what if the list contains values and as well as other lists. Like example
var list = new List<object>();
list.AddRange(new object [] {14,new List<int>(),new List<int>() {1,10,23}});
And here was the code someone came up with in C#
list.Flatten<int>().ToList().ForEach(Console.WriteLine);
static class Extensions
{
public static IEnumerable<T> Flatten<T>(this IEnumerable<Object> List)
{
var l = new List<T>();
foreach (var element in List)
{
if (element is T)
l.Add((T) element );
else
l.AddRange(((IEnumerable)element).Cast<T>());
}
return l;
}
}
First of all the code isn’t type safe. I know there is a better way to solve in C#, but I wanted to show how this can be solved in a terse manner with F#
And here is my solution to above problem using in F#
type T<'t> = |L of 't |N of T<'t> list let rec flatten l = match l with |L x -> [x] |N x -> List.concat(List.map flatten x) let tree = N[L 14;N[];N[L 1;L 10;L 23]] let result = flatten tree
[...] This post was mentioned on Twitter by Richard Laksana, Naveen. Naveen said: Flattening List in F# and C# http://bit.ly/aHLIwp #fsharp [...]
Tweets that mention Flattening List in F# and C# « Naveen's Blog -- Topsy.com
May 27, 2010 at 2:59 am
[...] Flattening List in F# and C# – “…similarities between F# and C# and one of the key things is the List module.” [...]
Weekly Link Post 147 « Rhonda Tipton's WebLog
May 30, 2010 at 9:35 pm