简体   繁体   中英

Using F# Datatypes in C#

More particularly, I really want an immutable/shared linked list, and I think having immutable maps and sets would be nice too. As long as I don't have to worry about the core implementation, I can easily add extension methods/subclass/wrap it to provide a reasonably slick external interface for myself to use.

Is there any reason I shouldn't do this? Performance, incompatibility, etc.?

FSharpx includes a couple of "adapters" so that F# collections can be used more comfortably in C#. Here's a short example:

var a = FSharpList.Create(1, 2, 3);
var b = a.Cons(0);
b.TryFind(x => x > 4)
 .Match(v => Console.WriteLine("I found a value {0}", v),
        () => Console.WriteLine("I didn't find anything"));

There's not much documentation right now, but you can use the tests for reference. It doesn't include absolutely every operation (I don't mind directly using things like MapModule in C# too much), but if you find anything you need missing, please fork the repository and add it!

I also blogged about this a few weeks ago.

Or you can try and use one of these implementations of persistent collections in C# .

The types in the F# library (such as Set , Map and list ) were not designed to be used from C#, so I wouldn't generally recommend using them directly. It can be done and some basic operations will work well (eg adding elements to an immutable map and checking if an element exists). However, there are some issues:

  • F# also has functionality in modules ( MapModule for an immutable map) and as a C# user, you would expect to see these as members.

  • F# functions are not represented as Func<_, _> delegates, but using some special F#-specific way. This means that using higher-order functions will be difficult.

So, in summary, I think that a better approach is to wrap the F# data type into a class (implemented in F#) that exposes the methods you need to a C# developer in a friendly way. You can eg easily declare an F# method that takes Func<_, _> delegate and calls F# higher-order function in a module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM