从文本文件读取并排序

贾夸

我设法读取了包含逐行随机数的文本文件。当我使用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

提前致谢。

如果所有行都是整数,则可以使用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

如果某些行可能不是有效的整数,则需要执行一个解析和验证步骤。例如:

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

请注意,tryParseInt我刚刚编写函数返回的是int值,所以我使用Seq.sort而不是Seq.sortBy int,并且该函数链的输出将是一个int序列,而不是一个字符串序列。如果您确实想要一个字符串序列,但是只有可以解析为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

请注意,我是如何s从此版本的中返回tryParseInt,以便Seq.choose保留字符串(但丢弃所有无法通过验证的字符串System.Int32.TryParse)。还有更多的可能性,但这应该给您足够的入门。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章