Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 273
epotter Avatar asked Dec 23 '08 21:12

epotter


People also ask

Can a list be passed to a function?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

Does C pass everything by value?

C always uses 'pass by value' to pass arguments to functions (another term is 'call by value', which means the same thing), which means the code within a function cannot alter the arguments used to call the function, even if the values are changed inside the function.


3 Answers

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.

like image 70
Alexey Romanov Avatar answered Oct 06 '22 09:10

Alexey Romanov


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);
like image 30
epotter Avatar answered Oct 06 '22 09:10

epotter


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

like image 29
Daniel Earwicker Avatar answered Oct 06 '22 11:10

Daniel Earwicker