2017-01-13 1 views
2

줄마다 임의의 숫자가 포함 된 텍스트 파일을 읽을 수있었습니다. printfn "%A" lines을 사용하여 출력 할 때 seq ["45"; "5435" "34"; ... ]이 나오므로 줄이 데이터 유형 목록이어야한다고 가정합니다. 텍스트 파일에서 읽기 및 정렬

open System 
let readLines filePath = System.IO.File.ReadLines(filePath);; 
let lines = readLines @"C:\Users\Dan\Desktop\unsorted.txt" 

는 지금 가장 최고에 의해 목록을 정렬하려고하지만 .sortBy() 방법이 없습니다. 어떤 사람이 수동으로이 작업을 수행하는 방법을 알려줄 수 있습니까? 그것을 배열 정렬하려면 시도했지만 그것을 작동하지 않습니다.

let array = [||] 
let counter = 0 
for i in lines do 
array.[counter] = i 
counter +1 
Console.ReadKey <| ignore 

미리 감사드립니다.

+2

목록이 아닌 일련입니다. ['Seq.sortBy'] (https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/seq.sortby%5B't,'key%5D-function-%5Bfsharp%5D)를 시도하십시오. – rmunn

+1

그래서'let sorted = lines.Seq.sortBy'와 같이 보일까요? @rmunn – KDOT

+1

아니요. 'Seq.sortBy'는 메소드가 아니라 함수입니다. 그것은'let sorted = Seq.sortBy int lines'이거나,'let sorted = lines |> Seq.sortBy int'입니다. – rmunn

답변

5

모든 라인이 정수가 있다면, 당신은 단지, Seq.sortBy int을 사용할 수 있도록 같은 라인의 일부가 유효 정수하지 않을 경우 다음 구문 분석과 검증을 통해 실행해야 할 것,

open System 
let readLines filePath = System.IO.File.ReadLines(filePath) 
let lines = readLines @"C:\Users\Dan\Desktop\unsorted.txt" 
let sorted = lines |> Seq.sortBy int 

단계. 예 :

I 단지 int 값을 반환 쓴 tryParseInt 함수 그래서 Seq.sort 대신 Seq.sortBy int, 그 기능 체인의 출력을 사용하는 것이 주 INT의 서열이 아닌 서열 될 것이다
let tryParseInt s = 
    match System.Int32.TryParse s with 
    | true, n -> Some n 
    | false, _ -> None 
let readLines filePath = System.IO.File.ReadLines(filePath) 
let lines = readLines @"C:\Users\Dan\Desktop\unsorted.txt" 
let sorted = lines |> Seq.choose tryParseInt |> Seq.sort 

문자열의. 당신이 정말로 문자열의 순서 만의 int로 해석 될 수있는 유일한 문자열을 원한다면, 당신은 이런 식으로 일을 할 수 :

let tryParseInt s = 
    match System.Int32.TryParse s with 
    | true, _ -> Some s 
    | false, _ -> None 
let readLines filePath = System.IO.File.ReadLines(filePath) 
let lines = readLines @"C:\Users\Dan\Desktop\unsorted.txt" 
let sorted = lines |> Seq.choose tryParseInt |> Seq.sortBy int 

주 내가 있도록 tryParseInt이 버전에서 s을 반환하고있어 방법 Seq.choose은 문자열을 유지하지만 (System.Int32.TryParse을 통해 유효성 검사에 실패한 문자열을 버립니다). 더 많은 가능성이 있지만, 시작하기에 충분할 것입니다.

+0

['Seq.choose' 문서] (https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/seq.choose%5B't,'u%5D-function-%5Bfsharp%5D). – rmunn

+1

세부 사항이 마음에 들었던만큼,'let sorted = Seq.sortBy int lines'는 잘 작동했습니다. 그러나 +1 정보를 위해서, 또한'for x in for sorted'를 수행하여 각 숫자를 출력했습니다 :) – KDOT

2

모든 댓글은 유효하지만 나는 당신의 매우 긴급한 루프에 대해 좀 더 걱정하고 있습니다. 당신은 또한 사용할 수 있습니다 let sorted = Seq.sort lines

sorted |> Seq.length // to get the number of lines
sorted |> Seq.map (fun x -> x.Length) // to iterate over all lines and get the length of each line

:

open System.IO 

let file = @"c:\tmp\sort.csv" 
let lines = File.ReadAllLines(file) 

이 선을 정렬하려면 :

모든 라인을 읽으려면 : 그래서 여기

은 예입니다 목록 이해 구문 :
[for l in sorted -> l.ToUpper()]

Seq는 컬렉션의 모든 종류의 작동하지만 당신은 (변경 가능) 또는 목록 (F 번호 목록) 배열로 교체 할 수 있습니다.