Skip to content

Instantly share code, notes, and snippets.

@jaspervdj
Created August 22, 2011 13:45
Show Gist options
  • Save jaspervdj/1162402 to your computer and use it in GitHub Desktop.
Save jaspervdj/1162402 to your computer and use it in GitHub Desktop.
Count the number of newlines in a file (learning OCaml)
(* Fold over a file in chunks *)
let fold_file f x file_name =
let buffer = String.create 1024 in
let file = open_in file_name in
let rec go a =
let length = input file buffer 0 (String.length buffer) in
let a' = f a (String.sub buffer 0 length) in
if length > 0 then go a' else a' in
let r = go x in
close_in file;
r;;
(* Count the number of newlines in a buffer *)
let count_newlines s =
let rec go n i =
try
let i' = String.index_from s i '\n' in
go (n + 1) (i' + 1)
with Not_found -> n in
go 0 0;;
(* Compose the previous two functions to count the lines in a file *)
let newlines = fold_file (fun x s -> x + count_newlines s) 0 Sys.argv.(1);;
print_int newlines;;
print_newline ();;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment