Snippets

Cameron Presley Create a report with line count for every file in a directory

Updated by Cameron Presley

File FileLineCounter.fs Modified

  • Ignore whitespace
  • Hide word diff
 open System.IO
 open System
 
-printfn "Enter a directory"
-let directory = Console.ReadLine()
-
 let getFiles directory = 
     match Directory.Exists directory with
     | true -> Directory.GetFiles(directory) |> Option.Some
     let content = reader.ReadToEnd()
     content.ToCharArray() |> Array.fold (fun state item -> if item='\n' then state + 1 else state + 0) 0
 
-let printReport getFiles =
-    match getFiles () with
+let printReport directory =
+    match directory |> getFiles with
         | None -> printfn "Couldn't get any files from the directory."
         | Some files -> 
             let lineCounts = files |> Array.map (fun x -> countLines x)
-            Array.iter2 (fun x y -> printfn "File: %s - %i lines" x y) files lineCounts
+            Array.iter2 (fun x y -> printfn "File: %s - %i lines" x y) files lineCounts
+            
+// Example usage
+printfn "Enter a directory"
+Console.ReadLine() |> printReport
Created by Cameron Presley

File FileLineCounter.fs Added

  • Ignore whitespace
  • Hide word diff
+open System.IO
+open System
+
+printfn "Enter a directory"
+let directory = Console.ReadLine()
+
+let getFiles directory = 
+    match Directory.Exists directory with
+    | true -> Directory.GetFiles(directory) |> Option.Some
+    | false -> None
+
+let countLines (file:string) = 
+    use reader = new StreamReader(file)
+    let content = reader.ReadToEnd()
+    content.ToCharArray() |> Array.fold (fun state item -> if item='\n' then state + 1 else state + 0) 0
+
+let printReport getFiles =
+    match getFiles () with
+        | None -> printfn "Couldn't get any files from the directory."
+        | Some files -> 
+            let lineCounts = files |> Array.map (fun x -> countLines x)
+            Array.iter2 (fun x y -> printfn "File: %s - %i lines" x y) files lineCounts
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.