F#管道和LINQ

Rem*_*sen 1 .net linq f# pipeline

我开始学习F#。我发现很难从OO编程中改变主意。我想知道F#开发人员将如何编写以下内容:

“传统” C#

public List<List<string>> Parse(string csvData){
    var matrix = new List<List<string>>();
    foreach(var line in csvData.Split(Environment.NewLine.ToArray(), StringSplitOptions.None)){
        var currentLine = new List<string>();
        foreach(var cell in line.Split(','){
            currentLine.Add(cell);
        }
        matrix.Add(currentLine);
    }
    return matrix;
}
Run Code Online (Sandbox Code Playgroud)

“功能性” C#

public List<List<string>> Parse(string csvData){
    return csvData.Split(Environment.NewLine.ToArray(), StringSplitOptions.None).Select(x => x.Split(',').ToList()).ToList();
}
Run Code Online (Sandbox Code Playgroud)

问题是:下面的代码是否正确?

F#

let Parse(csvData:string) = 
    csvData.Split(Environment.NewLine.ToArray(), StringSplitOptions.None).ToList()
    |> Seq.map(fun x -> x.Split(',').ToList())
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 5

您的翻译对我来说看起来不错。在C#(如使用扩展方法的foo.Select(...))是大致相当于从使用管道和F#功能的ListSeqArray模块,这取决于哪个集合类型您使用的(例如foo |> Seq.map (...))。

这是完全正常的,从F#使用LINQ扩展方法,并将它们与F#构造混合,但我只会做,当没有相应的F#的功能,所以我可能会避免ToArray()ToList()样品,并写在:

open System

let Parse(csvData:string) = 
    // You can pass the result of `Split` (an array) directly to `Seq.map`
    csvData.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None)
    // If you do not want to get sequence of arrays (but a sequence of F# lists)
    // you can convert the result using `Seq.toList`, but I think working with
    // arrays will be actually easier when processing CSV data
    |> Seq.map(fun x -> x.Split(',') |> Seq.toList)
Run Code Online (Sandbox Code Playgroud)