Skip to content

Instantly share code, notes, and snippets.

@haliphax
Last active February 28, 2024 18:25
Show Gist options
  • Select an option

  • Save haliphax/49848313767b250991b9 to your computer and use it in GitHub Desktop.

Select an option

Save haliphax/49848313767b250991b9 to your computer and use it in GitHub Desktop.
Sum all of the lines in a given file which are integers
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