Skip to content

Instantly share code, notes, and snippets.

@rctay
Created February 17, 2014 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rctay/9045618 to your computer and use it in GitHub Desktop.
Save rctay/9045618 to your computer and use it in GitHub Desktop.
ocaml prologue for HackerRank (reading ints, |>, etc)
let (|>) v f = f v;;
let string_of_char_list (ls : char list) : string =
let s = String.make (List.length ls) '0' in
List.fold_left (fun i c -> s.[i] <- c; i+1) 0 ls;
s;;
let append_string (xs : string list) (ls : char list) : string list =
let s = string_of_char_list ls in
if String.length s = 0 then xs else (xs @ [s]);;
let read_words_on_line (sep:char -> bool) (s:string) : string list =
let len = String.length s in
let rec aux i cs acc =
if i = len then
append_string acc cs
else
let c = s.[i] in
let cs, acc =
if sep c then
[], append_string acc cs
else
(cs @ [c]), acc in
aux (i+1) cs acc in
aux 0 [] [];;
let is_space = String.contains " \n\r";; (* apparently they use \r too *)
let read_ints () = read_line () |> read_words_on_line is_space |> List.map int_of_string;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment