Last active
August 29, 2015 14:20
-
-
Save Leonidas-from-XIV/5156f5c195616ee9eee8 to your computer and use it in GitHub Desktop.
Slightly more idiomatic code for http://thebreakfastpost.com/2015/04/22/four-mls-and-a-python/
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
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