如何从F#中的文件中读取浮点数据

时间:2015-07-31 18:38:37

标签: f# c#-to-f#

我有一个带浮点数的文件,我想读取它并将值保存在数组中以进行一些数学运算。然后我需要在另一个文件中打印新数组。我找到的所有方法都将文件作为字符串读取,我也不知道如何将字符串转换为float数组。

1 个答案:

答案 0 :(得分:3)

If we could assume that each float in the file on its own line then you could do something like this:

open System
open System.IO    

let readFloats filePath = 
    let strs = File.ReadLines(filePath) // Read file line by line
    strs |> Seq.map (fun str -> System.Double.TryParse(str)) // TryParse returns pair (Boolean * float value). Boolean is true if string parsed correctly 
         |> Seq.filter (fun (success, _) -> success) // filters out wrong  (not parsed strings)
         |> Seq.map snd // transforms sequence of pairs (bool * float) into float only