Skip to content

Instantly share code, notes, and snippets.

@keleshev
Created February 19, 2016 10:11
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 keleshev/d273fd721c3d088dfb10 to your computer and use it in GitHub Desktop.
Save keleshev/d273fd721c3d088dfb10 to your computer and use it in GitHub Desktop.
open Core_kernel.Std
let (>>) f g x = g (f x)
module Row = struct
let parse_exn = String.split ~on:',' >> List.map ~f:Float.of_string
let to_string = List.map ~f:Float.to_string >> String.concat ~sep:","
let print = to_string >> print_endline
end
let folder sum line =
let row = Row.parse_exn line in
match sum with
| [] -> row
| _ when List.length sum = List.length row -> List.map2_exn ~f:(+.) sum row
| _ -> failwith "Inconsistent-length rows"
let () = match Sys.argv with
| [|_; filename|] ->
In_channel.(with_file filename ~f:(fold_lines ~init:[] ~f:folder))
|> Row.print
| _ -> failwith "Exactly 1 filename must be given"
@keleshev
Copy link
Author

You can inline Row functions to shorten it to 16 lines, but I find it less readable:

open Core_kernel.Std

let folder sum line =
  let row = String.split ~on:',' line |> List.map ~f:Float.of_string in
  match sum with
  | [] -> row
  | _ when List.length sum = List.length row -> List.map2_exn ~f:(+.) sum row
  | _ -> failwith "Inconsistent-length rows"

let () = match Sys.argv with
  | [|_; filename|] ->
      In_channel.(with_file filename ~f:(fold_lines ~init:[] ~f:folder))
      |> List.map ~f:Float.to_string
      |> String.concat ~sep:","
      |> print_endline
  | _ -> failwith "Exactly 1 filename must be given"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment