Text processing/2: Difference between revisions

Content added Content deleted
(→‎{{header|OCaml}}: tail recursive call should be outside of try)
Line 1,649: Line 1,649:


let strip_cr str =
let strip_cr str =
let last = pred(String.length str) in
let last = pred (String.length str) in
if str.[last] <> '\r' then (str) else (String.sub str 0 last)
if str.[last] <> '\r' then str else String.sub str 0 last


let map_records =
let map_records =
Line 1,658: Line 1,658:
aux (e::acc) tail
aux (e::acc) tail
| [_] -> invalid_arg "invalid data"
| [_] -> invalid_arg "invalid data"
| [] -> (List.rev acc)
| [] -> List.rev acc
in
in
aux [] ;;
aux [] ;;
Line 1,671: Line 1,671:
aux acc tl
aux acc tl
| [] ->
| [] ->
(List.rev acc)
List.rev acc
in
in
aux [] ;;
aux [] ;;


let record_ok (_,record) =
let record_ok (_,record) =
let is_ok (_,v) = (v >= 1) in
let is_ok (_,v) = v >= 1 in
let sum_ok =
let sum_ok =
List.fold_left (fun sum this ->
List.fold_left (fun sum this ->
if is_ok this then succ sum else sum) 0 record
if is_ok this then succ sum else sum) 0 record
in
in
(sum_ok = 24)
sum_ok = 24


let num_good_records =
let num_good_records =
Line 1,690: Line 1,690:
let li = split (regexp "[ \t]+") line in
let li = split (regexp "[ \t]+") line in
let records = map_records (List.tl li)
let records = map_records (List.tl li)
and date = (List.hd li) in
and date = List.hd li in
(date, records)
(date, records)


Line 1,696: Line 1,696:
let ic = open_in "readings.txt" in
let ic = open_in "readings.txt" in
let rec read_loop acc =
let rec read_loop acc =
let line_opt = try Some (strip_cr (input_line ic))
try
with End_of_file -> None
let line = strip_cr(input_line ic) in
in
read_loop ((parse_line line) :: acc)
with End_of_file ->
match line_opt with
close_in ic;
None -> close_in ic; List.rev acc
(List.rev acc)
| Some line -> read_loop (parse_line line :: acc)
in
in
let inputs = read_loop [] in
let inputs = read_loop [] in