Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

Mingle strings in OCaml

Hi there! The problem that I solved this time was a little cumbersome initially, cause even though I knew well how to iterate over lists, I had no idea how to iterate over strings. The solution I found was inspired in the functions to explode and implode strings . These functions use the string indices to explode the string, creating a char list, or implode a char list, creating a string. My goal was not to implode nor explode, but mingle two strings, alternating the chars in each of them. Example of input and output, together with the final result is below.

# input
abc
xyz
# output
axbycz
(* OCaml Code now! *)
open Core.Std;;
(* Read the two input strings *)
let a = read_line();;
let b = read_line();;

let mingle a b =
  let la = String.length a in
  let lb = String.length b in
  let total = la + lb in
  let s = String.create total in
  let rec m i =
    (* j = index for inputs *)
    let j = i / 2 in
    if i > (total - 1) then s
    else let () =
      (* i = index for output *)
      s.[i] <- a.[j];
      s.[i+1] <- b.[j];
      in m (i + 2); in
  m 0;;

print_string (mingle a b)

In OCaml, it is important for the then and else parts of the if to return the same type. Part of the problem was a side effect, setting indices, and had no return type. The let () = part lets me ignore it and just consider where it is returning the actual string.

Tags
comments powered by Disqus