문제

나는 이것이 다소 두꺼운 질문이라는 것을 알고 있지만 F#과 C#의 비교를 수행하려고 시도하고 F# 스크립트를 빌렸다. http://www.clear-lines.com/blog/post/nearest-neighbor-classification-part-2.aspx 테스트 작업 및 구문을 목적으로 C# 프로그램에서 동일하게 작동하는 작업을 수행하려고합니다. 이 부분은 더 큰 스크립트로, 주어진 데이터의 k-means 분석을 수행하는 F# 프로그램으로 변환하고 있습니다.

다음은 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 
도움이 되었습니까?

해결책

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# 개발자에게는 훨씬 더 유용 할 수 있습니다.

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