1. Michael O'Neill
  2. csci-350-lab1

Source

csci-350-lab1 / splitter.ml

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 input_list evens odds =
   match input_list with
   (* When the input list is empty, return the output lists *)
     [] -> evens, odds
   (* If the list isn't empty, check divisibility by 2, add to the appropriate
    * list, and recurse with the modified output lists. *)
   | h::t when h mod 2 = 0 -> splitter t (h::evens) odds
   | h::t -> splitter t evens (h::odds)
;;

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

print_endline ("Input: " ^ String.concat " " (List.map string_of_int (List.rev input_list)));
print_endline ("Evens: " ^ String.concat " " (List.map string_of_int evens));
print_endline (" Odds: " ^ String.concat " " (List.map string_of_int odds))