简体   繁体   中英

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

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 ac# 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.

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.

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);

你可以传递一系列的整数 - 它基本上都是支持IEnumerable<int>

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

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