1

我知道这是一个相当厚的问题,但我试图在 F# 和 C# 之间进行一些比较,并从http://www.clear-lines.com/blog/post/Nearest-Neighbor-Classification-part借用了一个 F# 脚本-2.aspx并试图从 C# 程序中获取等效操作,以测试操作和语法。这部分位于一个较大的脚本中,我将其转换为一个 F# 程序,该程序对给定数据执行 k-means 分析。

这是 F# 部分:

let elections =
    let file = @"C:\Users\Deines\Documents\Election2008.txt"
    let fileAsLines =
        File.ReadAllLines(file)
            |> Array.map (fun line -> line.Split(','))
    let dataset =
        fileAsLines
        |> Array.map (fun line ->
            [| Convert.ToDouble(line.[1]);
               Convert.ToDouble(line.[2]);
               Convert.ToDouble(line.[3]) |])
    let labels = fileAsLines |> Array.map (fun line -> line.[4])
    dataset, labels 

这是数据示例(Election2008.txt):

AL,32.7990,-86.8073,4447100,REP 
AK,61.3850,-152.2683,626932,REP 
AZ,33.7712,-111.3877,5130632,REP 
AR,34.9513,-92.3809,2673400,REP 
CA,36.1700,-119.7462,33871648,DEM 
CO,39.0646,-105.3272,4301261,DEM 
CT,41.5834,-72.7622,3405565,DEM 
DE,39.3498,-75.5148,783600,DEM 
DC,38.8964,-77.0262,572059,DEM 
FL,27.8333,-81.7170,15982378,DEM 
4

1 回答 1

4

您可以通过以下方式在 C# 中执行相同的基本操作:

Tuple<double[][], string[]> GetElections()
{
    var file = @"C:\Users\Deines\Documents\Election2008.txt";
    var fileAsLines = File.ReadLines(file).Select(line => line.Split(','));
    var dataset = fileAsLines.Select(line => new[] 
                                             { 
                                                 Convert.ToDouble(line[1]),
                                                 Convert.ToDouble(line[2]),
                                                 Convert.ToDouble(line[3])
                                             }).ToArray();
    var labels = fileAsLines.Select(line => line[4]).ToArray();
    return Tuple.Create(dataset, labels);
}

话虽如此,C# 开发人员很少会以这种方式编写它。您更有可能创建一个自定义类型来保存结果(带有名称+值),并以这种方式读取它,即:

class ElectionResult
{
     public ElecationResult(string label, double x, double y, int amount)
     {
         this.Label = label;
         this.Point = new Point(x,y);
         this.Amount = amount;
     }
     string Label { get; private set; }
     Point Location { get; private set; }
     int Amount { get; private set; }
}

IList<ElectionResult> GetElectionResults()
{
    var file = @"C:\Users\Deines\Documents\Election2008.txt";
    var fileAsLines = File.ReadLines(file).Select(line => line.Split(','));

    return fileAsLines.Select(line => new ElectionResult(line[4],
                                                 Convert.ToDouble(line[1]),
                                                 Convert.ToDouble(line[2]),
                                                 Convert.ToInt32(line[3]))
                      .ToList();
}

这使得它对典型的 C# 开发人员更加有用,因为没有模式匹配可以从 Tuple 结果中提取数组。

于 2013-11-06T23:22:22.727 回答