Source

csci-350-lab1 / splitter.ml

Full commit
print_endline("Splits a list into two based on divisibility by 2.");;

(* File reader takes an input channel and a list to read into.
 * Contents within list are in reverse order relative to file. *)
let rec fr ic l =
   try
      fr ic l@[(int_of_string (input_line ic))]
   with
      End_of_file -> l
;;

(* Takes an input list and two output lists (one even and one odd). *)
let rec splitter ll e o = 
   match ll with 
   (* When the input list is empty, return the output lists *)
     [] -> e,o
   (* If the list isn't empty, check divisibility by 2, add to the appropriate
    * list, and recurse with the modified output lists. *)
   | h::t -> if (h mod 2) = 0 then (splitter t (h::e) o) else (splitter t e (h::o))
;;

(* Create an input channel. *)
let ic = open_in "input.dat" in
(* Read into a list. *)
let ilist = fr ic [] in 
(* Call splitter with empty lists; they'll be populated as splitter runs. *)
let e,o = splitter ilist [] [] in

print_endline ("Input: " ^ String.concat " " (List.map string_of_int ilist));
print_endline ("Evens: " ^ String.concat " " (List.map string_of_int e));
print_endline (" Odds: " ^ String.concat " " (List.map string_of_int o))