Rash thoughts about .NET, C#, F# and Dynamics NAV.


"Every solution will only lead to new problems."

Sunday, 12. October 2008


F# option types und generische Listen in C# verwenden

Filed under: C#,F# — Steffen Forkmann at 14:08 Uhr

Luis Fallas beschreibt in seinem Blog (“Exploring Beautiful Languages”) an einem sehr schönen Beispiel, wie man die F# option types mit Hilfe von Extension Methods in C# verwenden kann.

Hier ist eine generische Variante zu seiner Exists()-Methode:

open System.Runtime.CompilerServices

[<Extension>]
module Extensions =
  [<Extension>]
  let Exists(opt : 'a option) =
    match opt with
      | Some _ -> true
      | None –> false

Auf ähnlichem Wege kann man übrigens auch die generischen F#-Listen in System.Collections.Generic.List<T> umwandeln:

[<Extension>]    
let ToCSharpList(list : 'a list) =
  let csharpList = 
    new System.Collections.Generic.List<'a>()
  list |> List.iter (fun item -> csharpList.Add item)
  csharpList

Der umgekehrte Weg (von C# nach F#) ist fast analog, allerdings muss man die Liste drehen:

static class Extensions
{
  /// <summary>
  /// Converts a System.Collections.Generic.List<T> 
  /// in the corresponding F# list.
  /// </summary>
  public static Microsoft.FSharp.Collections.List<T> 

     ToFSharpList<T>(this List<T> list)
  {
      var fSharpList = 
        Microsoft.FSharp.Collections.List<T>.Empty;
      for (int i = list.Count - 1; i >= 0; i--)
       fSharpList = 
          Microsoft.FSharp.Collections.List<T>.Cons(
            list[i], 
            fSharpList);
      return fSharpList;
  }
}
Tags: , , , , , ,

No Comments »

No comments yet.

RSS feed for comments on this post. | TrackBack URI

Leave a comment

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> .