Reputation: 15812
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.?
Upvotes: 2
Views: 1084
Reputation: 99750
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#.
Upvotes: 7
Reputation: 243096
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 (e.g. 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 e.g. easily declare an F# method that takes Func<_, _>
delegate and calls F# higher-order function in a module.
Upvotes: 5