문제

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:

let func (param:(int64 * string) list) = 
  [ for n, s in param -> n, s, "new val" ]

I added the annotation (int64 * string) list to 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 using param:list<int64 * string> which might be easier to read.

If you wanted to use .NET List type (which is not usually recommended in F#), you can use the F# alias ResizeArray and write:

let func (param:(int64 * string) ResizeArray) = 
  ResizeArray [ for n, s in param -> n, s, "new val" ]

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 for to 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 :-)):

let func (param:(int64 * string) ResizeArray) = 
  let res = new ResizeArray<_>()
  for n, s in param do
    res.Add(n, s, "new val")
  res

You could also use higher-order functions like List.map and write:

let func (param:(int64 * string) list) = 
  params |> List.map (fun (n, s) -> n, s, "new val")

다른 팁

Here is a literal translation:

member __.Fun (param:ResizeArray<int64 * string>) =
    ResizeArray(param |> Seq.map (fun (a, b) -> a, b, "new val"))

This isn't very idiomatic, however.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top