Created
August 22, 2011 13:45
-
-
Save jaspervdj/1162402 to your computer and use it in GitHub Desktop.
Count the number of newlines in a file (learning OCaml)
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
(* 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