2016-03-04 133 views
3

的名單列表我有一個數據集像這樣轉換逗號分隔的字符串列表,以整數

1,2 
3,4 
5,6 
7,8 
9,0 

當我使用ReadAllLines我得到一個字符串數組讀取它。到目前爲止,我已經轉換的字符串列表數組包含字符串,如

[["1";"2"];["3";"4"]... etc 

我需要最後一步算一步吧,現在得到這個[[1;1;[1;4]... etc

我的代碼:

module Data = 
    let load(path : string) (filename : string) = 
     System.IO.File.ReadAllLines(path + "\" + filename) 
     |> Array.toList 
     |> Seq.map (fun s -> s.Split [|','|] |> Array.toList) 
     |> Seq.map (fun s -> s |> Seq.map System.Int32.Parse) 

這是我測試它時返回的結果

val it : seq<seq<int>> = seq [seq [1; 2]; seq [3; 4]; seq [5; 6]] 

我在等待這樣的事情

val zz : int list list = [[1; 2]; [3; 4]] 

回答

5

就快,現在你只需要序列的序列轉換成列表的列表:

|> Seq.map Seq.toList 
|> Seq.toList 

,你可以刪除線|> Array.toList這是在這種情況下更好地工作與序列,然後轉換爲列表作爲最後一步。

另請注意,您可以使用System.IO.Path.Combine(path, filename),它將處理爲您合併路徑和文件名的邏輯。

最後有一些重構,你可以這樣做:

|> Seq.map (fun s -> s |> Seq.map System.Int32.Parse) 

應用eta reduction可以刪除拉姆達:

|> Seq.map (Seq.map System.Int32.Parse) 

然後

|> Seq.map (fun s -> s.Split [|','|] |> Array.toList) 
|> Seq.map (fun s -> s |> Seq.map System.Int32.Parse) 
|> Seq.map Seq.toList 

可以簡化爲一個單一的map因爲x |> map f |> map g等於x |> map (f >> g)

|> Seq.map ((fun s -> s.Split [|','|]) >> Seq.map System.Int32.Parse >> Seq.toList) 

消除括號:

|> Seq.map (fun s -> s.Split [|','|] |> Seq.map System.Int32.Parse |> Seq.toList) 

可以去除中間值lines並鍵入註釋因爲Combine預計兩個字符串。下面是完整的代碼:

open System 
module Data = 
    let load path filename = 
     IO.File.ReadAllLines(IO.Path.Combine(path, filename)) 
      |> Seq.map (fun s -> s.Split [|','|] |> Seq.map Int32.Parse |> Seq.toList) 
      |> Seq.toList 
3

使用List.map而不是Seq.map:在這兩個

[|"1,2"; "3,4"; "5,6"; "7,8"; "9,0"|] 
|> Array.toList 
|> List.map (fun s -> s.Split [|','|] |> Array.toList |> List.map System.Int32.Parse) 

結果:

[|"1,2"; "3,4"; "5,6"; "7,8"; "9,0"|] 
|> Array.toList 
|> List.map (fun s -> s.Split [|','|] |> Array.toList) 
|> List.map (fun s -> s |> List.map System.Int32.Parse) 

既然你在一排有兩個map S,你可以將它們組合案例:

> 
val it : int list list = [[1; 2]; [3; 4]; [5; 6]; [7; 8]; [9; 0]] 
相關問題