I want to process the data present in file "persons.txt". But i have tried everything to process all the lines from text file.
The only way i can process data is by creating the list manually.
let myList = ["John"; "23"]
I want the program to iterate through all the lines of the text file. I have managed a way to pass all the content of the text file into a list but i can+t seem to move on from that stage.
My way of thinking is:
Can you please guide me?
Thanks!!
open Printf
(* FILE CONTENTS *)
(*
John;23;
Mary;16;
Anne;21;
*)
let file = "data/persons.txt"
;;
(* READ FROM EXTERNAL FILE *)
let read_lines name : string list =
if Sys.file_exists (name) then
begin
let ic = open_in name in
try
let try_read () =
try Some (input_line ic)
with End_of_file -> None
in
let rec loop acc =
match try_read () with
| Some s -> loop (s :: acc)
| None -> close_in_noerr ic; List.rev acc
in
loop []
with
e -> close_in_noerr ic;[]
end
else
[]
;;
(...)
Your question is not at all clear. Here are some observations:
First, your read_lines
function doesn't return the input in the form you need.
What read_lines
returns looks like this:
["John;23;"; "Mary;16;"; "Anne;21;"]
But what you want is something more like this:
[("John", "23)"; ("Mary", "16"); ("Anne", "21")]
The key here is to split the strings into pieces using ;
as a separator. You can probably use String.split_on_char
for this.
Second, you are not defining a function to calculate an answer from paramters. Instead your calculation is based on global variables. This won't generalize.
Instead of saying this:
let adult_check_condition =
... using global age and name ...
You need to define a function:
let adult_check_condition age name =
... use parameters age and name ...
Then you can call this function with different ages and names.