Last active
February 28, 2024 18:25
-
-
Save haliphax/49848313767b250991b9 to your computer and use it in GitHub Desktop.
Sum all of the lines in a given file which are integers
This file contains hidden or 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
| open System.IO | |
| // sums up all of the lines in a given file | |
| let sumFile (fileName:string) = | |
| // wrapper for catching int conversion exceptions | |
| let wrapper (sr:System.IO.StreamReader) = | |
| try | |
| int (sr.ReadLine()) | |
| with | |
| | :? System.FormatException -> 0 | |
| // sequence generator for lines in the file | |
| let readLines (path:string) = seq { | |
| use sr = new StreamReader(path) | |
| while not sr.EndOfStream do | |
| yield wrapper sr | |
| } | |
| // sum them all together | |
| Seq.sum (readLines fileName) | |
| [<EntryPoint>] | |
| let main_sumFile (argv:array<string>) = | |
| // 1 value provided; sum the given file; clean exit | |
| if argv.Length = 1 then | |
| printfn "%d" (sumFile argv.[0]) | |
| 0 | |
| // wrong number of parameters; display help message; dirty exit | |
| else | |
| printfn "Syntax: SumFile.exe <file name>" | |
| 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment