Made OCaml version slightly shorter, slightly more in functional style. Still could use improvement to remove side effects.