Naveen's Blog

Software dev interested in .NET, windbg and anything on the way

Flattening List in F# and C#

with 2 comments

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
About these ads

Written by Naveen

May 25, 2010 at 2:14 pm

Posted in C#, F#

2 Responses

Subscribe to comments with RSS.

  1. [...] This post was mentioned on Twitter by Richard Laksana, Naveen. Naveen said: Flattening List in F# and C# http://bit.ly/aHLIwp #fsharp [...]

  2. [...] Flattening List in F# and C# – “…similarities between F# and C# and one of the key things is the List module.” [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: