Created
June 2, 2011 05:49
-
-
Save nagat01/1003997 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I'm trying to translate C# code to F# for my training | |
// http://www.fincher.org/tips/Languages/csharp.shtml | |
open System | |
open System.IO | |
// A. Hello world program | |
let helloWorld = Console.WriteLine "Hello World!" | |
// C. Read and print an entire file | |
let readAll = // a. | |
let contents = System.IO.File.ReadAllText @"C:\sample.txt" | |
// Below is 3 ways of writing output | |
// I don't know why but it requires type annotation for Console.WriteLine | |
// (Console.WriteLine:string->unit) <| "contents = " + contents | |
// "contents = " + contents |> Console.WriteLine | |
Console.WriteLine("contents = " + contents) | |
let getFileAsString fileName = // b. | |
let mutable streamReader : StreamReader = null | |
let mutable contents = null | |
try | |
let fileStream = new FileStream(fileName,FileMode.Open, FileAccess.Read) | |
streamReader <- new StreamReader(fileStream) | |
contents <- streamReader.ReadToEnd() | |
finally | |
if streamReader <> null then streamReader.Close() | |
contents | |
let readAllLines = // c. | |
let lines = System.IO.File.ReadAllLines @"Sample.txt" | |
Console.WriteLine("contents={0}",lines.Length) | |
let readAllByStream = // d. | |
let sr = new StreamReader "Sample.txt" | |
while not sr.EndOfStream do | |
sr.ReadLine() |> Console.WriteLine | |
// D. Writing stuff | |
let writeAll = // a. | |
let myText = "Line1" + Environment.NewLine + "Line2" + Environment.NewLine | |
System.IO.File.WriteAllText(@"C:\sample2.txt",myText) | |
let writeAllByStream = | |
let fileStream = new FileStream("C:\sample2.txt",FileMode.OpenOrCreate,FileAccess.Write) | |
let streamWriter = new StreamWriter(fileStream) | |
try streamWriter.WriteLine "Howdy World." | |
finally if streamWriter<>null then streamWriter.Close() | |
let writeCreatedTime = | |
for i in 0..5000 do | |
using (File.CreateText(String.Format(@"C:\sandbox\sample{0}.txt",i))) | |
(fun w-> | |
let msg=string DateTime.Now + "," + string i | |
w.WriteLine msg | |
Console.WriteLine msg | |
) | |
Console.ReadLine() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment