epotter
epotter

Reputation: 7799

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

Upvotes: 7

Views: 2694

Answers (4)

epotter
epotter

Reputation: 7799

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

Upvotes: 3

Alexey Romanov
Alexey Romanov

Reputation: 170919

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.

Upvotes: 8

Daniel Earwicker
Daniel Earwicker

Reputation: 116764

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

Upvotes: 1

t3rse
t3rse

Reputation: 10124

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

Upvotes: 0

Related Questions