How to write a F# method equal to the below c# code? tried to google it but couldn’t find any working ones. thanks.
public List<Tuple<long, string, string>> Fun(List<Tuple<long, string>> param)
{
var ret = new List<Tuple<long, string, string>>();
foreach (var tuple in param)
{
ret.Add(new Tuple<long, string, string>(tuple.Item1, tuple.Item2, "new val"));
}
return ret;
}
If you want to use idiomatic functional lists, then you can write:
I added the annotation
(int64 * string) listto make sure that you get the same type as the one in your C#. If you didn’t add it, then the F# compiler would infer the function to be generic – because it actually does not matter what is the type of the first two elements of the tuple. The annotation can be also written in a C# style notation usingparam:list<int64 * string>which might be easier to read.If you wanted to use .NET
Listtype (which is not usually recommended in F#), you can use the F# aliasResizeArrayand write:This creates an F# list and then converts it to .NET
List<T>type. This should give you exactly the same public IL signature as the C# version, but I would recommend using F# specific types.As a side-note, the second example could be implemented using imperative F# code (using
forto iterate over the elements just like in C#). This generates exactly the same IL as C#, but this is mainly useful if you need to optimize some F# code later on. So I do not recommend this version (it is also longer :-)):You could also use higher-order functions like
List.mapand write: