Skip to content

Instantly share code, notes, and snippets.

@Leonidas-from-XIV
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leonidas-from-XIV/5156f5c195616ee9eee8 to your computer and use it in GitHub Desktop.
Save Leonidas-from-XIV/5156f5c195616ee9eee8 to your computer and use it in GitHub Desktop.
let split_by = Str.regexp ","
let read_line chan =
match input_line chan with
| c -> Some c
| exception End_of_file -> None
let rec fold_channel f acc chan =
match read_line chan with
| Some line -> fold_channel f (f line acc) chan
| None -> acc
let values_of_line line =
line
|> Str.split split_by
|> List.map float_of_string
let add_to values totals =
match totals with
| [] -> values
| _ ->
if List.length totals = List.length values then
List.map2 (+.) totals values
else failwith "Inconsistent-length rows"
let sum_channel chan =
let folder line = add_to @@ values_of_line line in
fold_channel folder [] chan
let sum_and_print_file filename =
let chan = open_in filename in
sum_channel chan
|> List.map string_of_float
|> String.concat ","
|> print_endline;
close_in chan
let main () =
match Sys.argv with
| [| _; filename |] -> sum_and_print_file filename
| _ -> failwith "Exactly 1 filename must be given"
let () = main ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment