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

About Naveen
Write code.

2 Responses to Flattening List in F# and C#

  1. Pingback: Tweets that mention Flattening List in F# and C# « Naveen's Blog -- Topsy.com

  2. Pingback: Weekly Link Post 147 « Rhonda Tipton's WebLog

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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: