学習の記録−6

ファイルの内容を読んでリストにするには

let contents = Array.toList(System.IO.File.ReadAllLines @"input.txt");;

みたいに書く。内容を画面に出したい時は

contents |> List.iter (printfn "%s");;
contents |> List.iter (fun x -> printfn "%s" x);;
contents |> List.iter (fun x -> Console.WriteLine(x));;
contents |> List.map  (fun x -> printfn "%s" x);;

みたいに書く。List.mapはunit型返してくる奴だと文句言われるんで、iterを使ったほうがいいらしい(実践F#より)

上の発展として、指定したファイルの奇数行(1行目除く)だけ読み込むために以下のように書いてみた。

let x = 
    System.IO.File.ReadAllLines @"input.txt"
    |> Array.toList
    |> List.mapi (fun i x -> (i,x))
    |> List.filter (fun x -> (fst x) % 2 = 0 && ((fst x ) <> 0))
    |> List.map (fun x -> snd x);;
//check
List.iter (fun y -> printfn "%s" y) x;;