Access F # list from inside C # code

I wrote an F # module that has a list inside:

module MyModule type X = { valuex : float32 } let l = [ for i in 1 .. 10 -> {valuex = 3.3f}] 

Now, from the C # class, I'm trying to access a previously defined list, but I don't know how to convert it:

 ... list = MyModule.l ; //here my problem 

I need something like:

 IList<X> list = MyModule.l; 

How can i achieve this?

+6
source share
2 answers

Easier than:

 IList<MyModule.X> list = MyModule.l.ToList(); 

The reason you need a conversion method, rather than cast / implicit conversion, is because FSharpList<T> implements IEnumerable<T> , but not IList<T> , because it is an immutable linked list.

Note that you need to include FSharp.Core as a reference in your C # project.

+10
source

FSharpList<T> (which is a .Net name of type F # list<T> ) does not implement IList<T> because it does not make sense.

IList<T> is for accessing and modifying collections that the index can access, but list<T> not. To use it from C #, you can explicitly use this type:

 FSharpList<MyModule.X> l = MyModule.l; var l = MyModule.l; // the same as above 

Or you can use the fact that it implements IEnumerable<T> :

 IEnumerable<MyModule.X> l = MyModule.l; 

Or, if you need IList<T> , you can use LINQ ToList() , as Ani suggested:

 IList<MyModule.X> l = MyModule.l.ToList(); 

But you must remember that the F # list is immutable and therefore there is no way to change it.

+5
source

Source: https://habr.com/ru/post/902227/


All Articles