What can I do to pass a list from C# to F#?

南楼画角 提交于 2019-12-07 01:19:46

问题


I know that the f# list is not the same at the c# List. What do I need to do to be able to pass a list of ints from a c# application to an f# library? I'd like to be able to use pattern matching on the data once it's in the f# code.


回答1:


You can use

Seq.toList : IEnumerable<'a> -> list<'a>

to convert any IEnumerable<'a> seq to an F# list. Note that F# lists are immutable; if you want to work with the mutable list, you don't need to do anything special, but you won't be able to use pattern matching. Or, rather, you can define active patterns for System.Collections.Generic.List<'a>; it's just a bad idea.




回答2:


Here is how I ended up doing it.

The FSharp code:

let rec FindMaxInList list = 
   match list with
   | [x] -> x
   | h::t -> max h (FindMaxInList t)
   | [] -> failwith "empty list"

let rec FindMax ( array : ResizeArray<int>) =
   let list = List.ofSeq(array)
   FindMaxInList list

The c Sharp code:

    List<int> myInts = new List<int> { 5, 6, 7 };
    int max = FSModule.FindMax(myInts);



回答3:


You can pass a sequence of ints - it's basically anything that supports IEnumerable<int>.




回答4:


You can reference C# Assemblies from F# projects. Expose your list via a referenced assembly.



来源:https://stackoverflow.com/questions/390176/what-can-i-do-to-pass-a-list-from-c-sharp-to-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!